以编程方式添加UITableView - 如何设置单元格的重用标识符?

6
我有一个UIViewController,在某个时候会增加一个UITableView,当它增加时,我只需初始化TableView实例变量并将其添加到视图中,但我不确定如何处理从视图中取消排队的单元格; 我需要一个重用标识符,但我不确定如何设置它。
在这个方法中,我该怎么做?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"wot";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    return cell;
}

你需要在cellForRowAtIndexPath的任何实现中做相同的事情。获取表格视图的方式不会改变表格视图的工作方式。你展示的代码是一个完美的起点。 - matt
2个回答

7

使用方法 initWithStyle:reuseIdentifier

  1. 检查 cell 是否存在
  2. 如果不存在,则需要初始化它。

代码

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath (NSIndexPath*)indexPath 
{
    static NSString *cellIdentifier = @"wot";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    if (!cell)
        cell = [[UITableViewCell alloc] initWithStyle: someStyle reuseIdentifier: cellIdentifier];

    return cell;
}

从iOS 5开始,您无需检查!cell。https://dev59.com/9VzUa4cB1Zd3GeqP57rj - Gabriele Petronella
因为与 IB 不同,我无法使用 UIView(UILabel、UIImage 等)为所有单元格提供特定的布局,所以我必须为每个单元格创建一个 UILabel 并将其添加到单元格的子视图中吗? - Doug Smith
你可以创建UITableViewCell的子类,并在那里进行特定的子视图设置。 - MJN
1
如果您使用Gabriele的建议,则需要使用registerClass:forCellReuseIdentifier:方法将子类化的UITableViewCell类注册到表视图中。 - MJN

0

重用标识符不需要显式定义。在cellForRowAtIndexPath方法中,您在问题中包含的定义已足以使用。

参考链接

例如

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyReuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:MyIdentifier]];
    }
    Region *region = [regions objectAtIndex:indexPath.section];
    TimeZoneWrapper *timeZoneWrapper = [region.timeZoneWrappers objectAtIndex:indexPath.row];
    cell.textLabel.text = timeZoneWrapper.localeName;
    return cell;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接