LoginSignup
0
0

More than 1 year has passed since last update.

【UIKit】コードからAutoLayoutでSafeArea対応させる方法

Posted at

AutoLayoutで配置したViewが画面上部のStatusBarなどに被らないよう、SafeAreaに対応させる方法を紹介する。

anchorで設定する方法

myView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
  • 対応させたいViewのanchorにsafeAreaLayoutGuideのanchorを設定する。
  • 基本的にはこの方法で良いと思われる。

画面の端からSafeAreaの広さ分スペースを空ける方法

myView.topAnchor.constraint(equalTo: view.topAnchor, constant: view.safeAreaInsets.top).isActive = true
  • equalToにはviewのanchorを設定しておき、そこからconstantに設定した値の分スペースを空ける。
  • safeAreaInsetsでSafeAreaのサイズが取得できるため、上下左右から対応させたいものを記述する。
  • bottomAnchorとrightAnchorの場合はconstantにマイナスの値を設定する必要がある。例: constant: -view.safeAreaInsets.bottom
  • safeAreaInsetsの値はviewDidLoad()内だと取得できないため、この方法を使う場合はanchorの設定をviewWillLayoutSubviews()などに記述する必要があるため注意。
0
0
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
0