LoginSignup
1
2

More than 5 years have passed since last update.

autolayoutとsafearea

Posted at

目的

iPhoneX対応を調査してる段階で、AutoLayoutで、理解を曖昧にしてる部分を見直そうと思った。
ついでに、safeAreaも理解しておかないと、この先に進めなさそうだったので、そこもまとめてみる。

view表示の大まかな流れ

  • Viewの読み込み
  • 制約の追加(AutoLayout)
  • 制約を元にViewのframeを計算(レイアウト)
  • frameの位置に描画(レンダリング)

思ったのは

viewDidLayoutSubviewsとかで、レイアウト更新すると、
再度描画し直すので、処理が重くなるっぽい。

最終調整したいなら、viewDidAppearかな?

autolayout使ってるなら、constraintを積極的に使う。

流れの説明部分の図

スクリーンショット 2018-11-14 7.05.36.png

boundsとframeの違いについて

いままでちゃんと理解してなかったので、しっかり理解してみた。

frame

x,yのポジションは親viewからの位置を示す
サイズはboundsと一緒かな

bounds

x,yは自分からの位置を示すので、基本(0.0)

イメージ図

こんな感じ

frame_vs_bounds.png

safeareaに関して

iPhoneXが導入されたことによって、出てきたもの。
iPhoneX以上のサイズのデバイスでは、必須。

safeAreaの領域

添付の図のような感じ
スクリーンショット 2018-11-14 17.48.31.png

safeAreaのサイズを取得するために

それ以外の機能も備えてるが、view系のデータをまとめて管理するため、以下のファイルを作成
```
//
// ViewManager.swift
// shotworks_customer
//
// Created by 平塚 俊輔 on 2018/11/12.
// Copyright © 2018 ‚àö√á≈ì√Ñ‚Äö√¢‚Ä¢‚àö√ᬨ‚àû‚àö‚àÇ ‚Äö√Ñ‚àû‚àö‚àè‚àö¬ß‚àö√£¬¨‚à´‚àö√Ü. All rights reserved.
//

import Foundation

/// view系の値管理
struct ViewManager {

static let rootViewController = UIApplication.shared.keyWindow?.rootViewController

static let statusBarHeight = UIApplication.shared.statusBarFrame.size.height

static var currentWindow: UIWindow? {
    if let window = UIApplication.shared.keyWindow {
        return window
    } else {
        return UIApplication.shared.windows[safe:0]
    }
}

// デフォルトFloat(44)としてUnwrap
static func navigationBarHeight(callFrom: UIViewController) -> CGFloat {
    return callFrom.navigationController?.navigationBar.frame.size.height ?? 44
}

// デフォルトFloat(44)としてUnwrap
static func tabBarHeight(callFrom: UIViewController) -> CGFloat {
    return callFrom.tabBarController?.tabBar.frame.size.height ?? 52
}


/// topのsafeArea
static var topSafeArea: CGFloat{

    if #available(iOS 11.0, *) {
        return ViewManager.currentWindow?.safeAreaInsets.top ?? 0
    }else{
        return 0
    }
}

/// bottomのsafeArea
static var bottomSafeArea: CGFloat{

    if #available(iOS 11.0, *) {
        return ViewManager.currentWindow?.safeAreaInsets.bottom ?? 0
    }else{
        return 0
    }
}

}


# 参照
https://qiita.com/shtnkgm/items/f133f73baaa71172efb2

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