Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When "draw" is called by UIKit?

I have a done button with a IBAction as following:

@IBAction func done() {
    print("Done pressed");
    let hudView = HudView.hud(inView: (navigationController?.view)!, animated: true)
    print("Set text");
    hudView.text = "Toggled"
}

The HudView is a subclass of UIView has a convinience constructor

class func hud(inView view: UIView, animated: Bool) -> HudView
{
    print("Constructor is called")
    let hudView = HudView(frame: view.bounds)
    hudView.isOpaque = false
    view.addSubview(hudView)
    view.isUserInteractionEnabled = false
    return hudView
}

And also I overwrite the draw method in it.

override func draw(_ rect: CGRect) {
    print("Draw is called")
    ...
}

The problem is that I don't understand why it prints out in such sequence

Done pressed
Constructor is called
Set text
Draw is called

Why is the draw method not called until I set the text? Why not immediately after it is constructed?

like image 348
Patroclus Avatar asked Oct 31 '25 09:10

Patroclus


1 Answers

According to Apple's Official Documentation.

This method is called when a view is first displayed or when an event occurs that invalidates a visible part of the view. You should never call this method directly yourself. To invalidate part of your view, and thus cause that portion to be redrawn, call the setNeedsDisplay() or setNeedsDisplay(_:) method instead.

When you initialise the view, it's not added to the view hierarchy and display for that view is not needed. So draw(_:) is not called. When you added the view as subview to the view hierarchy, it has to display and the method is called.

Somethings other than setNeedsDisplay() and setNeedsDisplay(_:) that trigger this method are when you make layouts to the view or change the size of the view.

like image 162
Cosmos Man Avatar answered Nov 01 '25 23:11

Cosmos Man



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!