开发中遇到的一个布局问题,cell上添加一个imageView显示图片,cell的高度跟随image的高度,但是image的位置始终不在预期的位置;
goodsImage = UIImageView()
goodsImage.image = UIImage.init(named: "分组大图.jpg")
self.addSubview(goodsImage)
goodsImage.snp.makeConstraints { (make) in
make.width.equalTo(kWidth)
make.top.equalTo(self.contentView)
make.bottom.equalTo(self.contentView)
}
用SnpKit布局,始终找不到原因;最后经同事指点,布局中
self.addSubview(goodsImage) 这里是self 而下面的相对位置用的是self.contentView self与self.contentView的区别是上面的子视图参考的父视图不一样。于是把代码改成下面,问题解决:
goodsImage = UIImageView() goodsImage.image = UIImage.init(named: "分组大图.jpg") self.addSubview(goodsImage) goodsImage.snp.makeConstraints { (make) in make.width.equalTo(kWidth) make.top.equalTo(self) make.bottom.equalTo(self) }
在其他地方的区别是:进行cell编辑时,比如cell内容向左移或者右移时,第一种方式子视图不会移动,第二可以,所以这种情况一般使用第二种方式。 还有在设置backgroundColor时,使用cell设置时左移或者右移颜色是不会变的,而用cell.contentCell设置时,移动后的空白会显示cell的默认颜色,这种情况视实际情况选择。