Interface Builder中具有可更改标签的可重用TableViewCell?

问题描述 投票:0回答:2

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

这甚至可能吗?据我了解,苹果最近一直在为Interface Builder中的自定义TableViewCell提供一些支持,所以应该可行吗?

Ps。我知道关于IB中TableViewCell的答案有很多问题,但是我找不到使标签正常工作的人。

iphone interface-builder cell tableview tableviewcell
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;
}

0
投票

我曾经用与接受答案相同的方式来做,但是我一直觉得自己使用的标签就像在Pascal中使用“ go to”一样。感觉很脏。但是也许只是我,标签可以正常工作。

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

interface MyCustomCell : UITableViewCell

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

@end

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

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9WU2M2SS5wbmcifQ==” alt =“在此处输入图像描述”>

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

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS83YXJPSi5wbmcifQ==” alt =“在此处输入图像描述”>“ >>

并且现在您可以在Table View数据源中访问此属性

#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;

}

使用标签容易出错,如果您经常使用它们,可能会很快变成一团糟。

© www.soinside.com 2019 - 2024. All rights reserved.