LoginSignup
7
3

More than 5 years have passed since last update.

[Swift]もうIBOutletでhogeHeightConstraintと書きたくない!

Last updated at Posted at 2018-10-05

hogeViewを作って
width heightをAutoLayoutで設定して
width heightをIBOutletでつなげて

hogeWidthConstraint.constant = 100

なんて書きたくない😭
という場合にもう少し簡単な方法です。

結論

ConstraintにIdentifierをつけます

スクリーンショット 2018-10-05 13.54.36.jpg

あとはこうです

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だとスッキリ書けます)

チーム開発の場合は受け入れられるか微妙なところですかね?
この方法とってるの一度も見たことがありません。

もっといい方法ないかな?🤔

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3