ios - 如何根据 "if"条件创建对象的不同子类

标签 ios uitableview

我在一个 Controller 中有 2 个 UITableView。每个表格都有自己的单元格原型(prototype),带有不同的 UITableViewCell 子类:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    if(tableView == self.commentsTable){
        CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentCell"];        
        cell.message.text = @"test";
    }else if(tableView == self.paramsTableView){
        RealtyParamCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RealtyParamCell"];
        cell.label.text = @"test2";        
    }

    return cell;
}

如果我这样做,最后一行会出现错误 return cell; : “使用未定义的标识符单元”但我无法定义 cell在一开始的时候:
UItableViewCell *cell;
if(tableView == self.commentsTable){
  <...>
}

因为我需要精确的单元格 - CommentCellRealtyParamCell

最佳答案

好吧,你仍然可以定义cell开始时

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    UItableViewCell *cell;
    if(tableView == self.commentsTable){
        CommentCell *commentCell= [tableView dequeueReusableCellWithIdentifier:@"CommentCell"];        
        commentCell.message.text = @"test";
        cell = commentCell;
    }else if(tableView == self.paramsTableView){
        RealtyParamCell *realtyParamCell = [tableView dequeueReusableCellWithIdentifier:@"RealtyParamCell"];
        realtyParamCell.label.text = @"test2";        
        cell = realtyParamCell;
    }

    return cell;

关于ios - 如何根据 "if"条件创建对象的不同子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23750696/

相关文章:

ios - UITableViewCell 中 iOS7 上的自动布局约束问题

ios - Swift Firestore - 从 Firestore 中删除表格单元格和删除文档

ios - Swift 作用域规则——设置非 nil 值后的 nil 值

ios - iOS XMPPFramework:如何解析didReceiveIQ?

ios - 如何使用圆角半径创建 UITableView 剖面 View

ios - 如何在 Swift 中向 TableView 添加自定义单元格?

iphone - 如何从其他 View 访问缓存

iOS 7 创建一个像 Photo 和 AppStore 一样的底部 UIToolbar

ios - 使用 Facebook 在照片中获取标记的人

php - 如何使用 PHP 发送 iOS 推送通知?