LoginSignup
4
2

More than 5 years have passed since last update.

親ViewのサイズいっぱいにAutoLayoutを設定するUIViewのextension

Last updated at Posted at 2018-05-24

addSubViewをしたけど、iPhoneの画面サイズによって正しく表示されないことがあると思います。
これを解決すべく、AutoLayoutを簡単に設定できるextensionを書いたので、メモです。

コード

AutoLayout.swift
import UIKit

extension UIView {

    /// Viewいっぱいにオートレイアウト
    func autoLayout(to toView: UIView) {
        self.translatesAutoresizingMaskIntoConstraints = false

        self.topAnchor.constraint(equalTo: toView.topAnchor).isActive = true
        self.bottomAnchor.constraint(equalTo: toView.bottomAnchor).isActive = true
        self.leftAnchor.constraint(equalTo: toView.leftAnchor).isActive = true
        self.rightAnchor.constraint(equalTo: toView.rightAnchor).isActive = true
    }
}

使い方

let view = UIView()
self.addSubview(view)
view.autoLayout(to: self)
4
2
5

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
2