drekka
drekka

Reputation: 21903

iPhone: Resizing in drawRect:

I have a UIView based control which I need to resize depending on various criteria and properties of the control. I'm not sure if the way I'm doing it is the best way but so far it's the only one I've found that seems to work. Because the size of the control is dependant on various properties, I cannot set the size in a constructor.

I have a method called setupControl: which contains all the code to finish the setup based on the properties set. I don't want setupControl: called manually, so in drawRect I detect if I need to call it and then queue a selector like this:

[self performSelector:@selector(setupControl)withObject:self afterDelay:0];
return;

At the bottom of setupControl: I then do:

[self setNeedsDisplay];
self.hidden = NO;

I've also overridden the initWithFrame: and initWithDecoder: constructors so that they set the UIView to be hidden to start with until the setup code is executed. The idea being to eliminate any "flashes" on the display as the control resizes.

As I said this works fine, the controls can be drawn ay size is the xib file and then set themselves to the correct size at run time.

My question is whether this method of queuing a selector, exiting the drawRect: and then using a setNeedsDisplay is the only way to do this? O is there some method I haven't found that I can override? or something else?

Upvotes: 1

Views: 860

Answers (1)

Kris Markel
Kris Markel

Reputation: 12112

What you probably want to override is layoutSubviews rather than drawRect as you're changing the layout, not implementing custom drawing.

You may also have to use a custom setter for any properties that change the size of the view and call [self setNeedsLayout] in the setter to make sure your layoutSubviews method is called before your view size is computed.

Upvotes: 3

Related Questions