Search code examples
iosswiftautolayoutsafearealayoutguide

How to specify offset from safe area in iOS below 11?


In iOS 11 I use

safeAreaInsets

to specify the offset from safe area to my custom view like this:

var frame: CGRect
if #available(iOS 11.0, *) {
    frame = CGRect(x:0,
                   y: self.view.safeAreaInsets.top + 16,
                   width: 100,
                   height: 50)
} else {
//backward compatibility to previous versions?
}

let customView = CustomView(frame: frame)

self.view.addSubview(customView)

the question is - how to specify offset from safe area in previous versions of iOS? Thanks in advance!


Solution

  • The versions of iOS before iOS 11 do not have safe area insets. These started with the introduction of iPhone X (shipped with iOS 11).

    There is no need to compensate for these insets on older versions of iOS.

    This is what your code should look like for backwards compatibility

    var frame: CGRect
    if #available(iOS 11.0, *) {
        frame = CGRect(x:0,
                       y: self.view.safeAreaInsets.top + 16,
                       width: 100,
                       height: 50)
    } else {
        frame = CGRect(x:0,
                   y: topLayoutGuide.length + 16,
                   width: 100,
                   height: 50)
    }
    
    let customView = CustomView(frame: frame)
    

    self.view.addSubview(customView)

    Note: If you are using the Safe Area Layout Guides for iOS 11, there are the topLayoutGuide and bottomLayoutGuide properties on UIViewController available for iOS 7 - 10.