I'm trying programmatically set constraints for some labels, buttons, and text fields relative to the height and width of the safe area. For example, I'm hoping to set the distance from the label from the top of the safe area to 10% of the safe area's height.
How can I retrieve the height and width of the safe area?
Is this a sound approach? My thought process was that my screen would then adjust automatically regardless of iOS device.
Thanks for the help!
override func viewDidLayoutSubviews()
super.viewDidLayoutSubviews()
let safeAreaHeight = view.safeAreaLayoutGuide.layoutFrame.height
let safeAraeWidth = view.safeAreaLayoutGuide.layoutFrame.width
}
Remember to do this in viewDidLayoutSubviews
function or setup your constraints in any function and then call that function inside viewDidLayoutSubviews
.
viewDidLoad
won't give you the safe area frames, as it runs before loading the view.
You can get the height by storing the frame of the safe area. safeAreaLayoutGuide
has a property named layoutFrame
.
let frame = self.view.safeAreaLayoutGuide.layoutFrame
print(frame.height)
print(frame.width)
I made an UIView
extension that creates a read-only property called safeAreaFrame
.
safeAreaFrame
will be the frame of the safe area if the iOS version is 11 or greater.
Otherwise, it will be bounds
(just the frame of the view).
extension UIView {
public var safeAreaFrame: CGRect {
if #available(iOS 11, *) {
return safeAreaLayoutGuide.layoutFrame
}
return bounds
}
}
Example:
let frame = self.view.safeAreaFrame
print(frame.height)
print(frame.width)
if #available(iOS 11.0, *) {
if let window = UIApplication.shared.keyWindow {
let safeAreaBottom = window.safeAreaInsets.bottom
let safeAreaLeft = window.safeAreaInsets.left
let safeAreaRight = window.safeAreaInsets.right
let safeAreaTop = window.safeAreaInsets.top
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With