4

目前,我使用 [aString sizeWithFont:constrainedToSize:lineBreakMode:] 正确调整了标签的大小,但是我已经在设备中引入了旋转并且具有灵活的宽度和高度,这导致我的 UILabel 拉伸宽度方式(因为它的设置相对于主视图)但不会在高度方面收缩以补偿额外的空间。

在我问的另一个问题中,有人告诉我使用sizeToFit和/或sizeThatFits:但是我在互联网上找不到任何有用的资源来告诉我如何适当地使用它,并且我所做的试验会导致不合理的行为。

简而言之,假设我有这样的结构:

UIView *innerView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width-20, 0)];
[innerView setAutoresizingMask:*flexible width and height*]
[innerView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:innerView];

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, innerView.frame.size.width-20, 0)];
[myLabel setAutoresizingMask:*flexible width and height*]
[myLabel setBackgroundColor:[UIColor blueColor]];
[myLabel setNumberOfLines:0];
[myLabel setLineBreakMode:UILineBreakModeWordWrap];
[innerView addSubview:myLabel];

那是一个简化版本(也是免责声明,这不是我的实际代码,我意识到这些元素会泄漏以及其他所有内容......这只是一个示例,因此您可以查看结构)。

基本上我有这两个元素。现在在旋转时,它们都会拉伸以适应新的视图大小。我需要的是一种增加或减少高度以动态适应内容的方法。[aString sizeWithFont...]只是静态的。那么我将如何使用sizeToFitsizeThatFits使这种动态化?

谢谢你。

汤姆

4

1 回答 1

2

您是否尝试在屏幕旋转后重置标签的框架?检查interfaceOrientation的值:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

然后,为didRotateFromInterfaceOrientation中的每个视图模式相应地设置标签的框架。

以下是针对字符串长度调整标签框架大小的示例:http: //cocoamatic.blogspot.com/2010/08/uilabel-dynamic-sizing-based-on-string.html

于 2011-01-21T19:16:20.603 回答