ios - 无法将 UITableViewDataSource 与自定义单元格一起使用

标签 ios swift uitableview

如果我使用自定义单元格 BaseCell,则无法导入 UITableViewDataSource。仅适用于 UITableViewCell 尽管 BaseCell 来自类型 UITableViewCell

import UIKit

class XptoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
    return 10
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> BaseCell {
    let cell = BaseCell()
    return cell
}

最佳答案

尝试相反的方法:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = BaseCell()
    return cell
}

但你可能想使用类似的东西:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("BaseCell") as? BaseCell
    return cell!
}

确保将“BaseCell”设置为单元标识符,如下所示: Sample of interface Builder

如果您遇到运行时错误,例如“展开可选时发现 nil”,您需要将 BaseCell 视为您的单元格的类,请参见图片: enter image description here

关于ios - 无法将 UITableViewDataSource 与自定义单元格一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43326701/

相关文章:

iOS - FCModel - 不传递空值时保存模型时出错

ios - 如何在 swift 中等到文本标签的 firstResponder 为 false

ios - 如何使用 Swift iOS 向 UIAlertView 按钮添加操作

ios - UITableViewController 中的死区

ios - Prototype Cell 在 ios 7+ 上有空白内容

ios - 如何从完成 block 安全地推送 View Controller ?

objective-c - 共享 UITableViewDelegate

ios - 来自移动应用程序的基于 token 的身份验证

ios - 设置 UIImage 动画的正确/干净的方法?

ios - UITableView 更改单元格样式