2

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!

Andrey M.
  • 3,021
  • 29
  • 42
  • Possible duplicate of [iOS 11 safe area layout guide backwards compatibility](https://stackoverflow.com/questions/46184197/ios-11-safe-area-layout-guide-backwards-compatibility) – Tamás Sengel Mar 10 '18 at 12:05

2 Answers2

4

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.

Sam
  • 649
  • 5
  • 13
  • Safe area insets have existed long before iOS 11. iOS 11 just revamped the safe area API to be more intuitive, including naming conventions. If you need to account for them in iOS 11, you should account for them in iOS 10. – trndjc Mar 10 '18 at 17:43
  • https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets Refer to this doc. Also it clearly specifies that safe area insets are only supported on iOS 11+. We had safe area layout guides for the top and bottom of the view to account for the stuff like the Tab bar and the nav bar – Sam Mar 11 '18 at 06:27
3
let safeAreaTop: CGFloat

if #available(iOS 11.0, *) {
    safeAreaTop = view.safeAreaInsets.top
} else {
    safeAreaTop = topLayoutGuide.length
}

let frame = CGRect(x:0, y: safeAreaTop + 16, width: 100, height: 50)
trndjc
  • 11,654
  • 3
  • 38
  • 51