11

我正在使用SnapKit,但找不到更新约束偏移的干净方法。这是一个简单的加载栏视图,其内部视图(expiredTime)必须根据百分比填充父级(从左到右)。

awakeFromNib我在自定义 UIView中创建约束

    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() 已被苹果提示重载:

不起作用:(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()
}
4

1 回答 1

17

您的第一个解决方案不起作用,因为您width在添加偏移量之前已经将 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()。您可以简单地调用约束的update方法(setNeedsUpdateConstraints()之后无需调用)

constraintWidth?.update(offset: CGFloat(percentage) * view.bounds.width)

请记住在0初始化时将宽度设置为constraintWidth

self.expiredTime.snp.makeConstraints { (make) in
    make.left.top.bottom.equalTo(self)
    self.constraintWidth = make.width.equalTo(0).constraint 
}
于 2017-02-13T20:52:11.393 回答