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

but*_*aby 17 ios swift

我正在尝试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
    }
}
Run Code Online (Sandbox Code Playgroud)

但我一直收到错误:

Missing return in a function expected to return 'UITableViewCell'
Run Code Online (Sandbox Code Playgroud)

在方法结束时我必须返回什么?

Fan*_*ini 30

出现错误是因为如果由于任何原因,表视图不是您编写的两个选项,那么它没有任何返回值,只需在末尾添加一个默认值:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView == firstTableView,
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomOne") as? CustomOneTableViewCell {
        return cell
    } else if tableView == autoSuggestTableView,
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTwo") as? CustomTwoTableViewCell {
        return cell
    }

    return UITableViewCell()
}
Run Code Online (Sandbox Code Playgroud)

更新到swift 4.1.2: 我已经更新了这个版本的答案4.1.2,因为return value该方法不能nil修改为默认的虚拟UITableViewCell.


rma*_*ddy 14

您的问题是编译器会查看两个if语句可能都是false 的可能性,并且在这种情况下您不会返回任何内容,因此会出错.

如果您只有两个表,最简单的更改是:

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
    }
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*wry 7

我对这个问题的首选解决方案是执行以下操作:

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

    return cellToReturn
}
Run Code Online (Sandbox Code Playgroud)

我认为这种方法保持了可读性和清晰度,同时也解决了错误。我不喜欢只为了兼容性而编写(危险的)代码,例如return nil.