hogeViewを作って
width heightをAutoLayoutで設定して
width heightをIBOutletでつなげて
hogeWidthConstraint.constant = 100
なんて書きたくない😭
という場合にもう少し簡単な方法です。
結論
ConstraintにIdentifierをつけます
あとはこうです
hogeView.constraints.filter { $0.identifier == "height" }.forEach { $0.constant = 100 }
さすがにワンライナーだと怒られそうなので、extensionにしちゃいましょう。
extension UIView {
func updateConstraint(identifier:String, value:CGFloat ) {
self.constraints.filter { $0.identifier == identifier }.forEach { $0.constant = value }
}
}
//利用側
hogeView.updateConstraint(identifier: "width",value: 100)
メリット:IBOutletが大量発生しない
デメリット:Identifierを設定し忘れたりする
別解(若干怪しい)
ConstraintのNSLayoutAttributeを見て、「hogeViewのWidthを変更する」みたいなこともできますね。
hogeView.constraints.filter { $0.firstAttribute == .width }.forEach { $0.constant = 100 }
extension UIView {
func updateConstraint(attribute:NSLayoutAttribute, value:CGFloat) {
self.constraints.filter { $0.firstAttribute == attribute }.forEach { $0.constant = value }
}
}
//利用側
hogeView.updateConstraint(attribute: .width,value: 100)
メリット:Identifierを書かなくていい
デメリット:attributeは、firstAttributeとsecondAttributeがある
attributeに対して自信がないなら使えなさそうです。
うっかりすると関係ないattributeを巻き込みそうで、私はまだ自信がないです。
attributeを固定したメソッドを作ると良いかもしれません。
(詳細について、時間があったら調べます。ちょっと調べた限りではスマートにはできなさそう?)
所感
(この方法は知ってたんですが、Objective-Cだと煩雑で嫌だったんですよね。Swiftだとスッキリ書けます)
チーム開発の場合は受け入れられるか微妙なところですかね?
この方法とってるの一度も見たことがありません。
もっといい方法ないかな?🤔