LoginSignup
0
2

More than 3 years have passed since last update.

UIKitのレイアウトをコードで組んだ時の備忘録

Last updated at Posted at 2020-07-20

UIをコードで組んだ時に

translatesAutoresizingMaskIntoConstraints = false

を入れてあげないと、自分が組んだUIレイアウトが優先されない。

自分の場合

レイアウトを組む際は、関数を定義してあげて使ってます。

func anchor(top: NSLayoutYAxisAnchor? = nil,
                left: NSLayoutXAxisAnchor? = nil,
                bottom: NSLayoutYAxisAnchor? = nil,
                right: NSLayoutXAxisAnchor? = nil,
                paddingTop: CGFloat = 0,
                paddingLeft: CGFloat = 0,
                paddingBottom: CGFloat = 0,
                paddingRight: CGFloat = 0,
                width: CGFloat? = nil,
                height: CGFloat? = nil) {
        translatesAutoresizingMaskIntoConstraints = false

こんな風に、書いてます。

これでanchor()を呼び出して使ってます。

使用例

let titleLabel : UILabel = {
    let label = UILabel()
    label.text = "hoge"
    label.font = UIFont.boldSystemFont(ofSize: 14)
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(titleLabel)
  titleLabel.anchor(top: view.safeAreaLayoutGuide.topAnchor,
            right: view.safeAreaLayoutGuide.rightAnchor,
            paddingTop: 50, paddingRight: 147, width: 100, height: 56)
  titleLabel.layer.cornerRadius = 56/2
}

みたいな感じで書いてあげればおそらくかけるのかなと思います。

image.png

こんな感じにできます。

レイアウトのコードは

https://github.com/tiking76/chatapp/blob/master/chatApp/Utiles/Extentions.swift

に置いてあります。

もっと詳しく知りたいよ!!ってひと

↓のスライドをみてね!

LTで登壇した時のスライド

レイアウトをコードで書いた時にアンカーのサイズ属性をよしなにやってくれるやつ(追記)

constraint(lessThanOrEqualToConstant:)

定義

func constraint(lessThanOrEqualToConstant c: CGFloat) -> NSLayoutConstraint

引数に入れるもの

このディメンションアンカーに関連付けられている属性の最大サイズを表す定数。

レイアウトの比較

変更前

image.png

変更後

image.png

使い方

//変更前
bubbleContainer.widthAnchor.constraint(equalToConstant: 250).isActive = true
//変更後
hogeContainer.widthAnchor.constraint(lessThanOrEqualToConstant: 250).isActive = true
0
2
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
0
2