1

假设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.这样做的正确方法是什么?

4

1 回答 1

2

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

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)
}
于 2017-04-16T18:33:01.233 回答