简体   繁体   中英

Overriding drawRect:(CGRect)rect in Objective-C (iOS)?

I was overriding the drawRect:(CGRect)rect method while making a simple iOS application. In the book I was reading, the bounds were defined using self.bounds as shown here:

- (void)drawRect:(CGRect)rect
{
    CGRect bounds = self.bounds;

    //rest of drawing code here
}

I noticed that in the book, the rest of the method did not even use the rect argument and worked fine. I assumed that rect would set the bounds in the view, so I tried the following:

- (void)drawRect:(CGRect)rect
{
    CGRect bounds = rect;

    //rest of drawing code here
}

(Obviously, I would not even need to make bounds equal to rect since I can refer directly to rect within the method.) I tried both ways and they yielded the same result. So are self.bounds and rect equal? If they are, I am assuming rect is used to set the bounds of the current view somewhere behind the scenes. But if they are not, what is the use of having rect as an argument to a method that does not even use it? Am I overlooking something obvious?

rect tells you which area you need to draw . It will always be less than or equal to self.bounds . As per the documentation (emphasis added):

The portion of the view's bounds that needs to be updated. The first time your view is drawn, this rectangle is typically the entire visible bounds of your view. However, during subsequent drawing operations, the rectangle may specify only part of your view.

If it's less efficient for you to draw subdivisions of your view then you might as well draw the whole thing.

In practice just drawing the whole thing is pretty much never a bottleneck so most people just do that as per the rule that the simplest code is preferable unless or until performance requires a different approach.

drawRect is written to pass in a rectangle that the method is supposed to draw. It's possible that the system may decide that only a portion of the view (perhaps because most of the view is covered by another view.

If only a portion of the view needs to be drawn, it can be faster to only draw that part.

As Tommy said while I was typing my answer, it is sometimes easier to just draw the entire view.

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