web-dev-qa-db-ja.com

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()を呼び出します。これにより、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()
}
_
8
jalone

オフセットを追加する前に、expiredTimeビューのwidthを全幅に設定しているため、最初のソリューションは機能しません。これを機能させるには、幅を_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)
_

constraintWidthを初期化するときは、幅を_0_に設定することを忘れないでください。

_self.expiredTime.snp.makeConstraints { (make) in
    make.left.top.bottom.equalTo(self)
    self.constraintWidth = make.width.equalTo(0).constraint 
}
_
12
joern