When I add a subview to a UIView
, or when I resize an existing subview, I would expect [view sizeToFit]
and [view sizeThatFits]
to reflect that change. However, my experience is that sizeToFit
does nothing, and sizeThatFits
returns the same value before and after the change.
My test project has a single view that contains a single button. Clicking the button adds another button to the view and then calls sizeToFit
on the containing view. The bounds of the view are dumped to the console before and after adding the subview.
- (void) logSizes {
NSLog(@"theView.bounds: %@", NSStringFromCGRect(theView.bounds));
NSLog(@"theView.sizeThatFits: %@", NSStringFromCGSize([theView sizeThatFits:CGSizeZero]));
}
- (void) buttonTouched {
[self logSizes];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(10.0f, 100.0f, 400.0f, 600.0f);
[theView addSubview:btn];
[theView sizeToFit];
[self performSelector:@selector(logSizes) withObject:nil afterDelay:1.0];
}
And the output is:
2010-10-15 15:40:42.359 SizeToFit[14953:207] theView.bounds: {{0, 0}, {322, 240}}
2010-10-15 15:40:42.387 SizeToFit[14953:207] theView.sizeThatFits: {322, 240}
2010-10-15 15:40:43.389 SizeToFit[14953:207] theView.bounds: {{0, 0}, {322, 240}}
2010-10-15 15:40:43.391 SizeToFit[14953:207] theView.sizeThatFits: {322, 240}
I must be missing something here.
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…