Reputation: 6971
I'm wondering which is the better way to calculate and obtain the final size of an UIView
that will be drawn dynamically. For example, I have a superview in wich a bunch of views will be drawn. I need the dimensions of those views to layout them properly, but its final size is dynamic taking into account the data they will be showing.
This way, I have to publish a class method to calculate and return the size of the view depending on the data to show, to create the view with the proper frame. After that, in the superview I layout the views correctly, and in the the drawRect
of the subview almost duplicate that class method code, because I need those calculations to draw properly.
Example:
+ (CGSize)sizeForTopText:(NSString *)topText
leftText:(NSString *)leftText
showingIcon:(BOOL)showIcon {
// Here I compute all this data taking into account font sizes,
// icon image size, etc, code that will be almost cloned in drawRect:
}
// In the superview
CGSize myViewSize = [MyView sizeForTopText:@"topText" leftText:@"leftText" showingIcon:NO];
MyView *theView = [[MyView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, myViewSize.width, myViewSize.height)];
I see that some Cocoa methods returns the final size after a draw, for example NSString's drawAtPoint:forWidth:withFont:fontSize:lineBreakMode:baselineAdjustment:
, which returns the final size of the text after drawing it with that parameters.
How can I achieve something like that? I don't like the current solution, I think it's wrong.
Thank you.
Upvotes: 0
Views: 173
Reputation: 299455
You generally shouldn't be calculating the size in drawRect:
. You should have all the data you need a the point that the data is updated. And calculating it in a class method seems a little odd (though maybe it's fine if you need to call it from various places, but that still is uncommon).
The normal way to do this is to override sizeThatFits:
for each subview. In there, calculate the optimal size based on the view's current configuration. Using sizeToFit
will then tell the view to take on its optimal size. Your superview can use override sizeThatFits:
to combine the results of its subviews, and you can use sizeThatFits:
in layoutSubviews
to calculate overall layout.
Upvotes: 1