【问题标题】:Modify frame of cell elements selected with viewWithTag does not work修改使用 viewWithTag 选择的单元格元素的框架不起作用
【发布时间】:2013-07-15 14:15:46
【问题描述】:

我在情节提要中有一个带有自定义单元格的表格视图

单元标识符为:MyCustomCellIdentifier

标签的框架是:{ { 15.0f, 178.0f }, { 280.0f, 40.0f } }

我基本上是想根据文本的大小来改变一个UILabel的框架。

假设我的 UILabel 在我的 StoryBoard 中被标记为:1

在函数中:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCustomCellIdentifier"];
    UILabel *myLabel = [(UILabel *)[cell viewWithTag:1];

    NSLog(@"frame %@", NSStringFromCGRect(myLabel.frame)); //frame {{0, 295}, {0, 0}}
    myLabel.text = @"myText";

    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, myLabel.frame.size.height);
    CGSize expectedLabelSize = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByTruncatingTail];
    CGRect newFrame = myLabel.frame;
    newFrame.size.width = expectedLabelSize.width;
    myLabel.frame = newFrame;
    NSLog(@"frame %@", NSStringFromCGRect(myLabel.frame)); //frame {{0, 295}, {80, 0}}

    return cell;
}

为什么有那些 0 值而不是情节提要中的实际值? 如何将标签的框架初始化为正确的值?

为什么如果我以编程方式设置值不会改变显示的标签框?

当我向下滚动并滚动回上一个单元格时,它实际上会显示正确的帧,但不是在第一次显示期间。

【问题讨论】:

    标签: ios uitableview uilabel frame


    【解决方案1】:

    这是自动布局开启的结果(默认开启)。要修复它,您可以关闭自动布局,或者使用约束而不是设置框架来更改标签的大小。我不清楚您为什么要尝试以这种方式设置标签的宽度——如果您只是在 IB 中将其设置为“适合内容的大小”,它将自动调整大小以适合文本(无论如何在宽度方向)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多