Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove safe area from UIView Programmatically in Swift?

Tags:

ios

swift

This is a custom view, this view creates a square with a given frame with the background color. I am adding a custom view to a subview, the view appears properly. But I am not able to cover the bottom safe area, anyone can help me to remove the safe area from bottom Programmatically.

class CustomView: UIView {
    
    override var frame: CGRect {
         
        didSet {
            setNeedsDisplay()   
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isOpaque = false
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.isOpaque = false
    }
    
    override func draw(_ rect: CGRect) {
                
        UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7).setFill()
        UIRectFill(rect)
        
        let square = UIBezierPath(rect: CGRect(x: 200, y: rect.size.height/2 - 150/2, width: UIScreen.main.bounds.size.width - 8, height: 150))
        let dashPattern : [CGFloat] = [10, 4]
        square.setLineDash(dashPattern, count: 2, phase: 0)
        UIColor.white.setStroke()
        square.lineWidth = 5
        square.stroke()
        
    }
       
}

1 Answers

Consider the following example:

class ViewController: UIViewController {

    private let myView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        configureCustomView()
    }

    private func configureCustomView() {
        myView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(myView)
        myView.backgroundColor = .systemPurple

        NSLayoutConstraint.activate([
            myView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            myView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            myView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            myView.heightAnchor.constraint(equalToConstant: 200)
        ])
    }
}

Result:
enter image description here

If you don't want to go over the safe area, then you could use myView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) inside NSLayoutConstraint.activate([...]). So you actually don't have to remove the SafeArea, because you can simply ignore them if you want so...

like image 129
finebel Avatar answered Nov 03 '25 05:11

finebel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!