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

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

问题描述

当我将子视图添加到 UIView 时,或者当我调整现有子视图的大小时,我希望 [view sizeToFit] [查看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天全站免登陆