NSLayoutのアンカーとUIViewのconstraintを使って
画像にある3色のUIViewでレイアウトを作ってみたのですが、
グリーンとレッド(ブルー)の間のconstraintが設定できません。
下記のコードではgreenView.anchorのleftを12と設定しているのですが、
シミュレーターには反映されず間に12のスペースが入りません。
何度も見直してはいるのですが、不備があればご指摘頂きたいです。
よろしくお願いします。
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let redView = UIView() redView.backgroundColor = .red let blueView = UIView() blueView.backgroundColor = .blue let greenView = UIView() greenView.backgroundColor = .green //each 各 [redView, blueView, greenView].forEach { view.addSubview($0) } redView.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: nil, bottom: nil, trailing: view.safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 12), size: .init(width: 125, height: 0)) //dimension 寸法 redView.heightAnchor.constraint(equalTo: redView.widthAnchor).isActive = true blueView.anchor(top: redView.bottomAnchor, leading: nil, bottom: nil, trailing: redView.trailingAnchor, padding: .init(top: 12, left: 0, bottom: 0, right: 0)) blueView.anchorSize(to: redView) greenView.anchor(top: redView.topAnchor, leading: view.safeAreaLayoutGuide.leadingAnchor, bottom: blueView.bottomAnchor, trailing: redView.leadingAnchor, padding: .init(top: 0, left: 12, bottom: 0, right: 12)) } } extension UIView { func anchorSize(to view: UIView) { widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true } func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, padding: UIEdgeInsets = .zero, size: CGSize = .zero) { translatesAutoresizingMaskIntoConstraints = false if let top = top { topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true } if let leading = leading { leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true } if let bottom = bottom { bottomAnchor.constraint(equalTo: bottom, constant: padding.bottom).isActive = true } if let trailing = trailing { trailingAnchor.constraint(equalTo: trailing, constant: padding.right).isActive = true } if size.width != 0 { widthAnchor.constraint(equalToConstant: size.width).isActive = true } if size.height != 0 { heightAnchor.constraint(equalToConstant: size.height).isActive = true } } }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/04/05 08:15
2018/04/05 08:24 編集
退会済みユーザー
2018/04/05 08:46 編集
2018/04/05 09:01
退会済みユーザー
2018/04/05 09:04