首页 文章

SizetoFit与UIViewAutoresizingFlexibleHeight . 有什么不同?

提问于
浏览
1

我一直被告知,如果我有一个带有动态文本内容的UILabel,我应该使用SizeToFit,因为它会正确调整UILabel . 我使用了sizeToFit但是在我滚动之后它弄乱了UITableViewCell上的文本标签 . 但是在初始屏幕加载时,它们看起来很好 .

在搞砸了几个小时后,我在某个地方看到其他人有同样的问题,而不是SizeToFit,他们使用了以下两行:

cell.message.lineBreakMode = UILineBreakModeWordWrap;
    cell.message.autoresizingMask = UIViewAutoresizingFlexibleHeight;

它会起作用 . 好吧,我做了,我的UILabels是完美的 . 但是我仍然很好奇理解为什么会这样?

所以现在我的代码看起来像:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MessagesCustomViewCell";
    MessagesCustomViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MessagesCustomViewCell_iPhone" owner:self options:nil];
        cell = [nib objectAtIndex:0];  //you can also loop thru or manually remember positions
    }

    NSArray * discussion = [self.messages objectAtIndex:indexPath.row];

      cell.author.text = [discussion valueForKeyPath:@"author.name"];
      cell.message.text = [discussion valueForKey:@"text"]; //DYNAMIC VARIABLE SIZED TEXT 


    cell.message.lineBreakMode = UILineBreakModeWordWrap;
    cell.message.autoresizingMask = UIViewAutoresizingFlexibleHeight;

    return cell;
}

1 回答

  • 4

    sizeToFit

    behavior:care about its content over superview's size

    sizeToFit 发送到没有 [yourLabel setNumberOfLines:0] 的UILabel会使标签尽可能宽,以适合它的文本 . 虽然用 [yourLabel setNumberOfLines:0] 你的标签会破坏它's text to mutiple lines according it'的宽度,但这会使它成为's height as large as possible to fit in it'的文字,它并不关心它's superview'的界限 .

    autoResizingMask

    behavior:care about superview's size over its content

    如果设置了UIlabel的autoResizingMask,一旦它的superview的边界发生变化,它将首先改变它的帧,然后检查“我可以在我的矩形中添加更多文本吗?”基于它的相对属性(numberOfLines,font,...) .

相关问题