简体   繁体   中英

What is more efficient, overriding drawRect or using viewWillAppear

I have several UITextView s in several ViewController s. In the past, when I have a couple of instances of needing a custom drawing for a TextView or Label , etc I would just adjust the drawing in viewWillAppear inside the VC that owned the UI object. This time, I will be needed several instances to be customized.

Would it be more appropriate to just create a subclassed UITextView and include the drawing code in drawRect versus having the same drawing code spread around several VC's. I am mainly worried about performance. Code maintainability is a secondary concern though.

To be clear, this is what I would use in drawRect:

- (void)drawRect:(CGRect)rect {
    self.layer.cornerRadius = 10;
    self.clipsToBounds = YES;
}

So after further testing, initWithFrame doesn't get called, but initWithCoder does. I have also found that initWithCoder is called once and so is drawRect . In my use case (a StaticCellTableView with the UITextView in a cell, what would the difference be?

You can include those 2 lines in init or initWithCoder (In case it's a xib or storyboard) method of the subclassed UITextView. Basically, this is just properties of the object - the don't need to run every time the UIView needs to refresh itself.

Create a ViewController baseclass, and then use that as the superclass for all your other VCs. You can then add this and other convenience methods to it and share the wealth so to speak.

In this particular case, putting it at the end of viewDidLoad would be a good place, as that is only messaged once, where viewWillAppear may be called multiple times. If you use viewdidLoad the code will be executed once.

I would not put those lines in the view's drawRect since that's called for every refresh. I'd recommend that you subclass UITextView and add those lines to the custom init method.

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