使用SnapKit自动调整UILabel大小

时间:2017-04-14 21:17:02

标签: swift uiview autolayout uilabel snapkit

我们假设CustomView's大小为300x300。 iconImageView具有其大小和分配的约束。我不知道UILabel中的文字有多长,所以我不想让UILabel的大小不变。我的目标是将左侧约束固定到iconImageView的右侧,将右侧约束到customView

override func updateConstraints() {
    super.updateConstraints()

    iconImageView.snp.updateConstraints { (make) in
        make.left.equalTo(customView).offset(10)
        make.centerY.equalTo(customView)
        make.size.equalTo(CGSize(width: 40.0, height: 40.0))
    }

    nameLabel.snp.updateConstraints { (make) in
        make.right.equalTo(customView).offset(-10)
        make.left.equalTo(iconImageView.snp.right).offset(10)
        make.centerY.equalTo(customView)
    }
}

当我尝试这种方法时,我收到错误:Unable to simultaneously satisfy constraints.有什么方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

好吧,我想你的子视图对顶部/底部约束一无所知,这意味着视图不知道如何重新布局自己。试试这个:

override func updateConstraints() {
    super.updateConstraints()

    iconImageView.snp.updateConstraints { (make) in
        make.left.equalTo(customView).offset(10)
        make.centerY.equalTo(customView)

        // Also from my point of view this line \/ 
        // is not very readable
        //  make.size.equalTo(CGSize(width: 40.0, height: 40.0))
        // Changed to:
        make.width.height.equalTo(40.0)
    }

    nameLabel.snp.updateConstraints { (make) in
        make.right.equalTo(customView).offset(-10)
        make.left.equalTo(iconImageView.snp.right).offset(10)

        // Add:
        make.top.equalTo(customView.snp.top)
        make.bottom.equalTo(customView.snp.bottom)
    }
}

如果你想保持"默认"标签的高度(如果是空字符串等),您可以添加:

make.height.greaterThanOrEqual(40.0)

同时自动布局和相框也不能很好地相互配合,因此您应该将自定义视图布局在" updateConstraints"方法,类似于:

customView.snp.updateConstraints { (make) in 
     make.edges.equalTo(self)
}