由于约束而导致图像拉伸

时间:2019-07-10 16:25:23

标签: swift uiimageview constraints

在表格单元格视图内设置单元格时,我遇到了一个简单的问题

 addSubview(profileImageView)
 addSubview(username)
 addSubview(postImageView)


 profileImageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
 profileImageView.leftAnchor.constraint(equalTo: leftAnchor,constant: 10).isActive = true
 profileImageView.widthAnchor.constraint(equalToConstant: 50).isActive = true
 profileImageView.heightAnchor.constraint(equalToConstant: 50).isActive = true
 selectionStyle = .none
 username.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 20).isActive = true
 username.topAnchor.constraint(equalTo: topAnchor,constant: 10).isActive = true
 username.rightAnchor.constraint(equalTo: rightAnchor).isActive = true

 //postImageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
 postImageView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
 postImageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
 postImageView.topAnchor.constraint(equalTo: profileImageView.bottomAnchor).isActive = true
 postImageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true

postImageView的对齐方式还可以,但是图像的高度拉伸得很多,并且图像变得拉伸了。我无法删除bottomAnchor或topAnchor,因为UI不能计算单元格的高度。

这是imageView。它可以是任何图像,因此高度是可变的

let postImageView : UIImageView = {
  let imgView = UIImageView()
  imgView.image = nil

  imgView.translatesAutoresizingMaskIntoConstraints = false
  imgView.clipsToBounds = true
  return imgView
}()

如何设置图像?我用翠鸟

if !(postImageUrl).isEmpty {
  postImageView.kf.setImage(with: URL(string: postImageUrl), placeholder: nil)
}else{
  postImageView.image = nil
}

为什么会这样?

注意:这与如何添加约束无关。我知道如何添加它们。

0 个答案:

没有答案