带子视图的可变UITableCellView高度

Can*_*der 8 iphone user-interface cocoa-touch uitableview

我想创建一个具有不同行高的UITableView,我试图通过在UITableViewCells中创建UILabel来实现这一点.

到目前为止,这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"EntryCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    }

    UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
    textView.numberOfLines = 0;
    textView.text = [entries objectAtIndex:[indexPath row]];
    [cell.contentView addSubview:textView];
    [textView release];

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

这给了我每个单元格2行文本.但是,每个"条目"具有不同的行数,我希望UITableViewCells自动调整大小,根据需要包装文本,而不更改字体大小.

[textView sizeToFit]和/或[cell sizeToFit]似乎不起作用.

这是我希望UITableView看起来的样子:

----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
Run Code Online (Sandbox Code Playgroud)

有谁知道如何正确地做到这一点?

谢谢.

Air*_*Ltd 11

UITableViewDelegate定义了一个可选的方法heightForRowAtIndexPath,它将帮助您入门.然后,您需要使用sizeWithFont.

这里有一些关于你的确切问题的讨论:

http://www.v2ex.com/2008/09/18/how-to-make-uitableviewcell-have-variable-height/

文本大小调整也在这个帖子中讨论过

  • Fwiw,v2ex.com链接已经死了,看起来这个域名被抓了. (4认同)