如何在Swift中以编程方式从UIView删除安全区域?

时间:2020-05-30 08:49:56

标签: ios swift

这是一个自定义视图,该视图创建具有给定框架和背景颜色的正方形。我将自定义视图添加到子视图,该视图正确显示。但是我无法覆盖底部的安全区域,任何人都可以以编程方式帮助我从底部移除安全区域。

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 个答案:

答案 0 :(得分:0)

考虑以下示例:

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)
        ])
    }
}

结果:
enter image description here

如果您不想越过安全区域,则可以在myView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)内使用NSLayoutConstraint.activate([...])。 因此,您实际上不必删除SafeArea,因为如果需要,您可以直接忽略它们...