当我将一个 subview 添加到UIView或调整现有 subview 的大小时,我希望[view sizeToFit][view sizeThatFits]能够反射(reflect)出这一变化。但是,我的经验是o​​jit_code不执行任何操作,并且sizeToFit在更改前后都返回相同的值。

我的测试项目有一个包含单个按钮的 View 。单击该按钮可将另一个按钮添加到 View ,然后在包含的 View 上调用sizeThatFits。在添加 subview 之前和之后, View 的边界都将转储到控制台。

- (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];
}

输出为:
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}

我一定在这里想念什么。

谢谢。

最佳答案

该文档对此非常清楚。 -sizeToFit几乎调用了-sizeThatFits:(可能以 View 的当前大小作为参数),而-sizeThatFits:的默认实现几乎不执行任何操作(仅返回其参数)。

一些UIView子类会覆盖-sizeThatFits:来做一些更有用的事情(例如,UILabel)。如果需要任何其他功能(例如,调整 View 的大小以适合其 subview ),则应子类化UIView并重写-sizeThatFits:

10-02 20:41