Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the height and width of the safe area?

Tags:

ios

swift

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!

like image 776
code_monkey Avatar asked Feb 25 '18 08:02

code_monkey


3 Answers

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.

like image 105
Simran Singh Avatar answered Oct 07 '22 17:10

Simran Singh


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)
like image 22
codeherk Avatar answered Oct 16 '22 17:10

codeherk


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
    }
}
like image 15
maxwell Avatar answered Oct 16 '22 19:10

maxwell