4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AutoLayoutの優先度をコードで書く

Last updated at Posted at 2023-03-17

はじめに

前に調べた時情報が見つからなかったのでメモ

NSLayoutConstraintクラスのpriorityプロパティに代入すればできるとアドバイス頂きました。

公式リファレンス
https://developer.apple.com/documentation/uikit/nslayoutconstraint#2882272

Storyboardを使わないプロジェクトの設定をします

やり方知らないかたはこちらの記事どうぞ.

コードです

今回はできるものはオートレイアウトの優先度は関係のないものです
書き方だけ参考になればと思います。

import UIKit

class ViewController: UIViewController {
    var topView: UIView!
    

    override func viewDidLoad() {
        super.viewDidLoad()
        view = UIView()
        view.backgroundColor = .white
        
        topView = UIView()
        topView.backgroundColor = .red
        topView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(topView)
        
        // オートレイアウトの制約
        let constraint = topView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        // レイアウトの制約を有効化
        constraint.isActive = true
        // オートレイアウトの優勢度
        constraint.priority = .defaultHigh
        // 優先度がの数値を確認
        print(constraint.priority)
        
        
        let constraints: [NSLayoutConstraint] = [
            topView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            topView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            topView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            topView.heightAnchor.constraint(equalToConstant: 100),
            
        ]
        NSLayoutConstraint.activate(constraints)
       
    }


}

ここで優先度変えてます。

// オートレイアウトの制約
        let constraint = topView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        // レイアウトの制約を有効化
        constraint.isActive = true
        // オートレイアウトの優勢度
        constraint.priority = .defaultHigh
        // 優先度がの数値を確認
        print(constraint.priority)

defaultHighとdefaultLowがあります。

        // オートレイアウトの優勢度
        constraint.priority = .defaultHigh //750
        // オートレイアウトの優勢度
        constraint.priority = .defaultLow //250

こうすると好きな数値入れられます。

        // オートレイアウトの優勢度
        constraint.priority = .init(rawValue: 333)

おわり

サンプルです
https://github.com/kabikira/AutoLayoutPriority

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?