无法设置UIImageView的大小

时间:2019-08-07 19:11:09

标签: swift uitableview uiimageview uistackview

我有一个UIImageView,我想给它一个固定的大小,但是它不起作用,UIImageView的大小不会改变。 这是我的UIImageView

private let profileImg: UIImageView = {
    let img = UIImageView(image: UIImage(named: "profileplaceholder"))
    img.contentMode = .scaleAspectFill
    img.layer.borderWidth = 1.0
    img.layer.borderColor = UIColor.appPurple.cgColor
    img.layer.cornerRadius = img.frame.width / 2
    img.clipsToBounds = true
    img.frame.size.width = 80
    img.frame.size.height = 80
    return img
}()

我将图像添加到UIStackView中,

private lazy var mStack: UIStackView = {
    let stack = UIStackView(arrangedSubviews: [self.profileImg, self.nickname, self.unfollowBtn])
    stack.translatesAutoresizingMaskIntoConstraints = false
    stack.distribution = .fill
    stack.axis = .horizontal
    stack.spacing = 1.0

    return stack
}()

1 个答案:

答案 0 :(得分:3)

StackView将调整其元素的大小。您应该给它固定大小的约束:

private let profileImg: UIImageView = {
...
    img.translatesAutoresizingMaskIntoConstraints = false
    img.heightAnchor.constraint(equalToConstant: 80).isActive = true
    img.widthAnchor.constraint(equalToConstant: 80).isActive = true
...
}()