user11798164
user11798164

Reputation:

how to remove safe area from UIView Programmatically in 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()
        
    }
       
}

Upvotes: 4

Views: 12872

Answers (2)

J A S K I E R
J A S K I E R

Reputation: 2184

In case you want to do this fast. (Not programatically)

  1. Open storyboard.
  2. Select your UIView.

enter image description here

  1. Safe Area should be unselected.

enter image description here

Upvotes: -2

finebel
finebel

Reputation: 2355

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...

Upvotes: 7

Related Questions