【问题标题】:How to initialize a custom tableview cell如何初始化自定义表格视图单元格
【发布时间】:2013-07-10 00:37:15
【问题描述】:

我正在使用情节提要和自定义单元格。我正在尝试搜索。它工作正常,并在加载 tableviewcontroller 时加载自定义单元格,一旦我输入搜索字符,返回的单元格是 UITableViewCellStyleDefault 并且我只能设置标签,我不确定它为什么不选择自定义单元格。有人可以帮忙吗。

抱歉,它重复了this,但我不知道它是如何工作的。

我正在使用此代码。

    static NSString *CellIdentifier = @"memberCell";
    MemberCell *cell = (MemberCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];        
    NSDictionary *item = self.searchList[indexPath.row];

    if (cell == nil) {
      cell = [[MemberCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:CellIdentifier];        
     }

     cell.memberFullName.text = [item[@"full_name"] uppercaseString] ;
     cell.memberPosition.text =  [item[@"title"] length] < 1 ? [NSString stringWithFormat:@"%@",  item[@"districts"]] : [NSString stringWithFormat:@"%@, %@", item[@"title"], item[@"districts"]];
     cell.memberRoom.text = [NSString stringWithFormat:@"Rm %@", item[@"room_number"] ];
    [cell.memberImage setImageWithURL:[NSURL URLWithString:item[@"image_thumb"]]
                 placeholderImage:[UIImage imageNamed:@"placeholder"]];

迪帕克

【问题讨论】:

    标签: iphone uitableview uistoryboardsegue


    【解决方案1】:

    您说“我正在尝试搜索” - 您的意思是您添加了 UISearchDisplayController 并且您正在尝试让您的自定义单元格出现在该结果表视图中?如果是这样,您有两个选择:

    1. tableView:cellForRowAtIndexPath: 方法中,您需要将自定义单元格从主表视图中取出,而不是从搜索结果表视图中取出。当您在故事板中的 tableview 中定义一个单元格时,故事板仅将其注册到该 tableview,因此它不能从任何其他 tableview 中出列(我在 WWDC '13 上与负责故事板的苹果工程师确认了这一点)。所以,代码应该是这样的:

      MemberCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    2. 将您的自定义单元格定义移动到一个独立的 xib 文件中(创建一个空的 XIB,从对象列表中拖动一个 UITableViewCell 并根据需要进行配置)。定义一个自定义单元格类并将其配置为 xib 中的单元格类,然后您可以使用 registerNib:forCellReuseIdentifier:

    3. 手动将该单元格类型注册到两个表视图中

    【讨论】:

    • 我使用了第一个,现在一切正常,除了高度搞砸了,[tableview:setRowHeight] 适用于主 tableview 但不适用于搜索结果。
    • UISearchDisplayController:didLoadSearchResultsTableView: 已修复
    • 如果是可变的,你也可以实现tableView:heightForRowAtIndexPath:来设置自定义行高