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

时间:2013-04-02 19:07:15

标签: iphone ios objective-c uitableview uiviewcontroller

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

在这种方法中我该怎么做?

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

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

    return cell;
}

2 个答案:

答案 0 :(得分:7)

使用方法initWithStyle:reuseIdentifier

  1. 检查cell是否存在
  2. 如果没有,则需要对其进行初始化。
  3. -(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;
    }
    

答案 1 :(得分:0)

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

一起使用

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