简体   繁体   中英

How draw(_ rect: CGRect) actually work?

I don't understand how this function actually work If I want to change Background Color of the "View" I will go to acces background property of the View and change value of it

let containerView = CustomView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
containerView.backgroundColor = UIColor.blue

But When I want to change color of the rectangle in draw() function I just call UIColor.green.set() function. Why this function change Color of the Rectangle

class CustomView: UIView {
    override func draw(_ rect: CGRect) {
        super.draw(rect)


        let rect = UIBezierPath(roundedRect: CGRect(x: 150, y: 150, width: 100, height: 100), cornerRadius: 5.0)
        UIColor.green.set()  // <- Why this line change rect color ?
        rect.fill()
    }
}

A UIView has a .backgroundColor property. When UIKit wants to display the view, it checks the .backgroundColor property and "fills" the background with that color.

UIColor.green.set() and rect.fill() does not change the background color of the view.

When you override the draw(_ rect: CGRect) function, UIKit has already done its processing of .backgroundColor property, and filled the background as necessary. Your code then "draws a filled rectangle" on the background.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM