ios - 如何在一个 View Controller 中使用两个自定义 UITableViewCells 创建两个 TableView ?

标签 ios swift

我正在尝试使用两个自定义 UITableViewCells 在一个 View Controller 中创建两个 UITableViews。我有以下内容:

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'

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

最佳答案

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

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()
}

更新到 swift 4.1.2: 我把这个答案更新到4.1.2版本了,也是因为方法的返回值不能为nil,修改为默认, 虚拟 UITableViewCell

关于ios - 如何在一个 View Controller 中使用两个自定义 UITableViewCells 创建两个 TableView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37447124/

相关文章:

ios - Swift Playground 执行已中止

iOS Swift - 调度组,异步调度

ios - UICollectionView 中的自动布局约束发生变化

ios - 如何检索现有场景中节点的位置?

ios - 在 Xcode 9(测试版)中将 pod 与 Playgrounds 结合使用

ios - Swift 3,将变量发送到第三个屏幕

ios - 当打开另一个通知时,如何防止通知从通知中心消失? iOS

ios - 如何在 iOS 中添加与 tableview 重叠的 View

ios - 使用 AVAudioPlayer 无法通过 Swift 4 播放 .m4a

ios - 带有颜色和居中文本的 UIImage