我使用
SnapKit并且找不到更新约束偏移的简洁方法.这是一个简单的加载栏视图,其内部视图(expiredTime)必须根据百分比填充父项(从左到右).
我在自定义UIView的awakeFromNib中创建约束
self.expiredTime.snp.makeConstraints { (make) in make.left.equalTo(self) make.top.equalTo(self) make.bottom.equalTo(self) self.constraintWidth = make.width.equalTo(self).constraint } setNeedsUpdateConstraints()
然后无论什么时候更新,我都会调用setNeedsUpdateConstraints(),这将触发默认的updateConstraints(),它已被Apple提示重载:
不起作用:( expiredTime视图始终适合父视图)
override func updateConstraints() { let offset = self.frame.width * CGFloat(percentage) self.expiredTime.snp.updateConstraints { (make) in make.width.equalTo(self).offset(offset).constraint } super.updateConstraints() }
这也行不通:
override func updateConstraints() { let offset = self.frame.width * CGFloat(percentage) self.constraintWidth?.update(offset: offset) super.updateConstraints() }
重建所有约束工作,但我想避免它
override func updateConstraints() { self.expiredTime.snp.remakeConstraints() { (make) in make.left.equalTo(self) make.top.equalTo(self) make.bottom.equalTo(self) self.constraintWidth = make.width.equalTo(self).multipliedBy(self.percentage).constraint } super.updateConstraints() }
解决方法
您的第一个解决方案不起作用,因为您已经在添加偏移量之前将expiredTime视图的宽度设置为整个宽度.要使其工作,您必须将宽度设置为0,然后添加偏移量.但是这里并不真正需要偏移,您可以简单地将宽度设置为计算出的宽度:
override func updateConstraints() { let width = self.frame.width * CGFloat(percentage) self.expiredTime.snp.updateConstraints { (make) in make.width.equalTo(width) } super.updateConstraints() }
或者,如果您保留对约束的引用,则根本不必覆盖updateConstraints().你可以简单地调用约束的更新方法(之后不调用setNeedsUpdateConstraints())
constraintWidth?.update(offset: CGFloat(percentage) * view.bounds.width)
只需记住在初始化constraintWidth时将宽度设置为0:
self.expiredTime.snp.makeConstraints { (make) in make.left.top.bottom.equalTo(self) self.constraintWidth = make.width.equalTo(0).constraint }