【问题标题】:Correct way to use sizeThatFits: and sizeToFit with UILabel?将 sizeThatFits: 和 sizeToFit 与 UILabel 一起使用的正确方法?
【发布时间】:2011-04-30 16:08:44
【问题描述】:

目前,我有一个使用 [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 来使这个动态化呢?

谢谢。

汤姆

【问题讨论】:

    标签: iphone resize uilabel sizetofit


    【解决方案1】:

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

    - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-09
      • 2013-11-06
      • 2013-12-01
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 2011-10-05
      相关资源
      最近更新 更多