根据从API中提取的数据调整TableViewCell的内容

时间:2013-07-28 20:54:04

标签: ios api layout uitableview

我正在尝试根据从API(图片+文字)中提取的内容来调整单元格的大小。

我现在已经设定了为图像,标题(两行)和描述(两行)留出空间。

问题:有时没有图片可用,有时标题只有一行,有时没有描述或1行描述; 所以我需要根据这些动态内容调整单元格的大小。

WebListCell.m

- (void)layoutSubviews {
    [super layoutSubviews];

    self.imageView.frame = CGRectMake(1, 20, 320, 180);
    self.headlineLabel.frame = CGRectMake(10, 210, 290, 40);
    self.descriptionLabel.frame = CGRectMake(10, 250, 290, 30);

    [self.headlineLabel setNumberOfLines:2];
    [self.headlineLabel sizeToFit];
    [self.descriptionLabel setNumberOfLines:2];
    [self.descriptionLabel sizeToFit];
}

WebListViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    Feed *feedLocal = [headlinesArray objectAtIndex:indexPath.row];
    NSString *headlineText = [NSString stringWithFormat:@"%@", feedLocal.headline];
    NSString *descriptionText = [NSString stringWithFormat:@"%@", feedLocal.description];
    cell.headlineLabel.text = headlineText;
    cell.descriptionLabel.text = descriptionText;
    }

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    WebListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WebListCell"];
    Feed *feedLocal = [headlinesArray objectAtIndex:indexPath.row];

    NSString *head = [NSString stringWithFormat:@"%@", feedLocal.headline];
    cell.headlineLabel.text = head;
    if (head.length > 100 ){
        [cell.headlineLabel setNumberOfLines:1];
    }
} // WARNING ALERT: "CONTROL REACHES END OF NON-VOID FUNCTION"

我有WebListCell.m列出单元格,然后WebListViewController.m调用WebListCell.m进行布局。我正确地提取了所有数据,但只是需要帮助调整大小并且无法弄明白,即使我已经在StackOverflow上查看了其他问题......任何人都可以帮忙解决这个问题?

现在我所拥有的不会调整单元格高度。

非常感谢,我会根据需要发布任何其他代码!

1 个答案:

答案 0 :(得分:0)

heightForRowAtIndexPath希望您返回一个浮点值,即单元格的高度。这是被提出的例外。

要计算字符串占用的垂直空间大小,可以使用以下方法:

CGSize size = [feedLocal.headline sizeWithFont:FONT 
                                      forWidth:WIDTH 
                                 lineBreakMode:NSLineBreakByWordWrapping];

return size.height + SOME_PADDING;

您需要尝试宽度和填充看起来很好。您在问题中提到了一些其他变量,但通常,这是您需要做的。