如何在一个视图控制器中使用两个自定义UITableViewCells创建两个表视图?

问题描述:

我试图创建一个使用两个自定义UITableViewCells二合一UITableViews视图控制器。我有以下几点:如何在一个视图控制器中使用两个自定义UITableViewCells创建两个表视图?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    if tableView == self.tableView { 
     let cell = tableView.dequeueReusableCellWithIdentifier("CustomOne") as! CustomOneTableViewCell 
     return cell 
    } 

    if tableView == self.autoSuggestTableView { 
     let cell = tableView.dequeueReusableCellWithIdentifier("CustomTwo") as! CustomTwoTableViewCell 
     return cell 
    } 
} 

但我不断收到错误:

Missing return in a function expected to return 'UITableViewCell' 

我有什么的方法结束返回?

+0

您需要在方法结尾处返回一些内容。如果'tableView'不是'self.tableView'或'self.autoSuggestTableView',该方法返回什么? – quant24

+0

@ quant24这已经涵盖在答案中。 – rmaddy

+0

@rmaddy谢谢,我注意到了太晚了。 – quant24

错误出现,因为如果因任何原因,表视图是不可的,你写了两个选项,那么它不没有任何价值可返回,只需在末尾添加return nil

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    if tableView == self.tableView { 
     let cell = tableView.dequeueReusableCellWithIdentifier("CustomOne") as! CustomOneTableViewCell 
     return cell 
    } else if tableView == self.autoSuggestTableView { 
     let cell = tableView.dequeueReusableCellWithIdentifier("CustomTwo") as! CustomTwoTableViewCell 
     return cell 
    } 

    return nil 
} 
+0

如果只有两个表格,它怎么可能不是两个表格中的一个? – Gruntcakes

+0

@ThePumpingLama该函数需要一个返回值,并且有一个不返回任何值的“道路”。 – Fantini

+0

@rmaddy是的,这是正确的,我认为这是你要管理的任何不受欢迎的行为如何做一个设计决策。 – Fantini

你的问题是,编译器会在这两个if声明可能是假的,你不要在这种情况下返回任何东西,因此错误的可能性。

如果你只有两个表,最简单的变化是这样的:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    if tableView == self.tableView { 
     let cell = tableView.dequeueReusableCellWithIdentifier("CustomOne") as! CustomOneTableViewCell 
     return cell 
    } else { 
     let cell = tableView.dequeueReusableCellWithIdentifier("CustomTwo") as! CustomTwoTableViewCell 
     return cell 
    } 
}