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 
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...