微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 更新SnapKit约束偏移量

我使用 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 
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐