2
3

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 5 years have passed since last update.

SafeAreaの外側までViewを表示する

Posted at

はじめに

iPhoneXが発表されてから約1年、SafeAreaについて標準のUIKitを使っていれば、特にiPhoneXについて深く意識することはありませんでした。今回、大きめの画像をSafeAreaの外側まで表示したいことがあって、どのように実現すれば良いかを色々試してみた結果を書いてみました。

やりたいこと

画像をiPhoneXのSafeAreaの外、特に上部に表示する。下部はSafeArea内が理想。
今回の記事では、UIImageViewの代わりにUIViewがSafeAreaの外まで表示できることを目標とします。

環境

Mac OSX 10.14
Xcode10
iOS12
Storyboard

実現方法

  1. コードによる実装
  2. Storyboardの設定
  3. NSLayoutConstraintの設定

コードから

参考
https://qiita.com/lovee/items/21131fb441a1a86b45e3
https://stackoverflow.com/questions/46192280/detect-if-the-device-is-iphone-x/47067296

UIView.safeAreaInsetsを確認し、コードで調整する方法。またはNSLayoutConstraintをサブクラス化してデバイス毎にTop Marginを調整する方法。

TopExtendableConstraint.swift
import UIKit

class TopExtendableConstraint: NSLayoutConstraint {

    override var constant: CGFloat {
        set {
             super.constant = newValue
        }
        get {
            return -1 * (UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0)
        }
    }    
    
    class var hasTopNotch: Bool {
        if #available(iOS 11.0, tvOS 11.0, *) {
            // with notch: 44.0 on iPhone X, XS, XS Max, XR.
            // without notch: 20.0 on iPhone 8 on iOS 12+.
            return UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0 > 24
        }
        return false
    }
    
}

サブクラス化したこのクラスをStoroyboard上もしくはコード上で指定すれば、今回のやりたいことが実現できました。しかし、若干面倒な方法だなと感じました。

Storyboardの設定を使う方法

参考:https://qiita.com/akatsuki174/items/407158d0d19c60d0020a
Storyboard設定の「Use Safe Area Layout Guidesのチェックボックスを外す」か
それぞれのViewの「Safe Area Layout Guideのチェックボックスを外す」で対応が可能
この方法だと、SafeAreaのTopとBottomの両方の外側に配置されました。今回はSafeAreaのTopのみ外に出したかったので、この方法では実現ができませんでした。

NSLayoutConstraintの設定を使う方法

今回、TopのみだけSafeAreaの外に配置したかったので、別な方法が必要でした。1つ目のコードによる対応の他にStoryboard上でできるかを調べてみたところ、以下の方法がありました。

スクリーンショット 2018-12-24 14.36.16.png

TopのConstraintに対して、First ItemもしくはSecond Itemの中で、対象がSuperviewSafeAreaの選択項目がありました。SafeAreaが選択されていたのでSuperviewに変えたところ、iPhoneXでSafeAreaの外まで配置されました。
今回はこの方法を使用しております。

終わりに

できるだけシンプルな方法で実現することができました。
iOSアプリ開発の知見はありますが、書くことに対してはあまり経験がないので、足らない部分がありましたらご指摘いただけると幸いです。

参考

https://ja.wikipedia.org/wiki/IPhone_X
https://qiita.com/roba4coding/items/5a0794cf7cd13c82b2b5
https://qiita.com/lovee/items/21131fb441a1a86b45e3
https://qiita.com/akatsuki174/items/407158d0d19c60d0020a
https://stackoverflow.com/questions/46192280/detect-if-the-device-is-iphone-x/47067296

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?