无法让 UIView sizeToFit 做任何有意义的事情 [英] Having trouble getting UIView sizeToFit to do anything meaningful

查看:21
本文介绍了无法让 UIView sizeToFit 做任何有意义的事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我向 UIView 添加子视图时,或者当我调整现有子视图的大小时,我希望 [view sizeToFit][view sizeThatFits] 以反映该更改.但是,我的经验是 sizeToFit 什么都不做,sizeThatFits 在更改前后返回相同的值.

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.

我的测试项目有一个包含单个按钮的视图.单击该按钮将另一个按钮添加到视图中,然后在包含的视图上调用 sizeToFit.在添加子视图之前和之后,视图的边界被转储到控制台.

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

输出是:

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.

谢谢.

推荐答案

文档对此非常清楚.-sizeToFit 几乎调用了 -sizeThatFits:(可能以视图的当前大小作为参数),而 -sizeThatFits: 的默认实现确实如此几乎没有(它只是返回它的参数).

The documentation is pretty clear on this. -sizeToFit pretty much calls -sizeThatFits: (probably with the view's current size as the argument), and the default implementation of -sizeThatFits: does almost nothing (it just returns its argument).

某些 UIView 子类覆盖 -sizeThatFits: 以做一些更有用的事情(例如 UILabel).如果您想要任何其他功能(例如调整视图大小以适应其子视图),您应该继承 UIView 并覆盖 -sizeThatFits:.

Some UIView subclasses override -sizeThatFits: to do something more useful (e.g. UILabel). If you want any other functionality (such as resizing a view to fit its subviews), you should subclass UIView and override -sizeThatFits:.

这篇关于无法让 UIView sizeToFit 做任何有意义的事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆