How do you ignore the safe area in UIKit?

2.8k Views Asked by At

I know you use ignoresSafeArea() in SwiftUI to make some UI-element-frame dismiss the safe area. However, when using UIKit I don't know how to do it. I want to place a UILabel right below the actual screen, but I cannot see it because it is hidden behind the safe area.

import UIKit

class SignInViewController: UIViewController {

    private let headline = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addLabel()
        view.backgroundColor = .black
        
        
    }
    
    func addLabel() {
        
        headline.text = "SmashPass"
        headline.textColor = UIColor.red
        headline.frame = CGRect(x: 0 , y: 0 , width: 243, height: 29)
        headline.textAlignment = .center
    
        // alignment
        headline.center.x = view.center.x
        headline.center.y = view.frame.minY - 10
        
        view.addSubview(headline)
        
    }

}
1

There are 1 best solutions below

1
DonMag On BEST ANSWER

Learn about how to use Auto-Layout...

Here is your code, with modifications to use Constraints and Auto-Layout to place the label at the bottom of the view:

class SignInViewController: UIViewController {
    
    private let headline = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addLabel()
        
        view.backgroundColor = .black
    }
    
    func addLabel() {
        
        headline.text = "SmashPass"
        headline.textColor = UIColor.red
        headline.textAlignment = .center
        
        // -- use Auto-Layout!
        // alignment
        //headline.frame = CGRect(x: 0 , y: 0 , width: 243, height: 29)
        //headline.center.x = view.center.x
        //headline.center.y = view.frame.minY - 10
        
        view.addSubview(headline)
        
        headline.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            // label uses full-width
            headline.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            headline.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            // constrain the label bottom to the view bottom
            headline.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            // label height is 29-points
            headline.heightAnchor.constraint(equalToConstant: 29.0),
        ])
        
    }
    
}

Note: in general, we want to constrain elements with awareness of the Safe-Area...

Using that code, we'll get this on an iPhone 12 Pro (for example):

enter image description here

and, if we set headline.backgroundColor = .yellow so we can see the label's frame:

enter image description here