【问题标题】:Programmatically adding a UITableView - how do I set the reuse identifier for the cells?以编程方式添加 UITableView - 如何为单元格设置重用标识符?
【发布时间】:2013-04-02 19:07:14
【问题描述】:

我有一个 UIViewController,它在某些时候会增长一个 UITableView,当它发生时,我只需初始化 TableView 实例变量并将其添加到视图中,但我不确定如何处理单元格的出列以添加到看法;我需要一个重用标识符,但我不知道如何设置它。

我在这个方法中做什么?

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

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

    return cell;
}

【问题讨论】:

  • cellForRowAtIndexPath 的任何实现中,您都会做同样的事情。您获得表格视图的方式并没有改变表格视图的工作方式。您展示的代码是一个非常好的开始。

标签: iphone ios objective-c uitableview uiviewcontroller


【解决方案1】:

使用方法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 开始,您无需检查 !cellstackoverflow.com/questions/7946840/…
  • 由于与 IB 不同,我可以为所有单元格提供带有 UIViews 的特定布局(UILabel、UIImage 等),因此我必须创建一个 UILabel 并将其添加到每个单元格的单元格子视图中?
  • 您可以创建 UITableViewCell 的子类并在那里进行特定的子视图设置。
  • 如果您使用Gabriele的建议,您需要使用registerClass:forCellReuseIdentifier:方法将您的子类UITableViewCell的类注册到表格视图中。
【解决方案2】:

无需明确定义重用标识符。在cellForRowAtIndexPath 方法中,您所包含的定义足以使用

Reference

例如

- (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;
}

【讨论】:

    猜你喜欢
    • 2015-02-26
    • 1970-01-01
    • 2012-06-26
    • 2020-10-18
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    • 1970-01-01
    相关资源
    最近更新 更多