0

如何在 Interface Builder 中使用可变标签制作可重用的 TableViewCell?

这甚至可能吗?据我了解,苹果最近一直在 Interface Builder 中给予自定义 TableViewCell 一些爱,所以这应该是可能的?

附言。我知道有很多关于 IB 中 TableViewCell 的答案的问题,但我找不到任何使标签起作用的人。

4

2 回答 2

1

您可以更改正在重复使用的单元格中的任何内容。要自定义您在 IB 中创建的标签,您应该在 IB 本身中设置它们的标签并使用相同的标签获取标签。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    MyCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil)
    {
        cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }


    // Configure the cell.
    //Do anything here with the labels. Even add or remove them.
    (UILabel*) label1 = (UILabel*)[cell viewWithTag:1];
    return cell;
}
于 2011-08-29T11:50:46.830 回答
0

我曾经以与接受的答案相同的方式这样做,但我一直觉得使用标签就像我在 Pascal 中使用“转到”一样。感觉很脏。但也许只有我,标签工作得很好。

不过还有另一种方法。子类化 UITableViewCell,创建 IBOutlet 属性,在 IB 中连接,并在cellForRowAtIndexPath:代码中引用您的属性。像这样:

interface MyCustomCell : UITableViewCell

@property (nonatomic, weak) IBOutlet UILabel *myAwesomeLabel;

@end

不要忘记在 IB 中将单元格的类设置为 MyCustomCell。

在此处输入图像描述

之后,您可以像这样直接在 IB 中连接您的财产

在此处输入图像描述

现在在您的表视图数据源中,您可以访问此属性

#import "MyCustomCell.h"


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:@"MyCell"];

    if (cell) {
        cell.myAwesomeLabel.text = @"Hello, World!";
    }

    return cell;

}

使用标签很容易出错,如果您使用大量标签,可能很快就会变得一团糟。

于 2015-05-14T09:37:38.317 回答