ios - 无法将 UITableViewCell 设置为单元格

标签 ios swift uitableview

我制作了一个 ViewController ,在该 ViewController 中,我制作了一个 TableView ,在 TableView我添加了一个 TableViewCell。 在 TableViewCell 中,我添加了一个文本标签和一个图像。 我制作了一个名为 customCell 的 cocoa touch 文件,并将其与 TableView Cell 连接起来。

ViewController 文件中我写了这样的内容:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

            let cell:customCell = tableView.dequeueReusableCellWithIdentifier("cell") as! customCell
            cell.imageCountry.image = UIImage(named: "2xd.png")
            cell.nameCountry.text = "hey"
return cell

这是我在 customCell 文件中编写的内容: 导入 UIKit

class customCell: UITableViewCell {

    @IBOutlet var imageCountry: UIImageView!
    @IBOutlet var nameCountry: UILabel!

}

我将 TableView 和 ViewController 与 DataSource 和 Delegate 连接起来。 当我运行代码时,出现以下错误:

Could not cast value of type 'UITableViewCell' (0x10d1119f0) to 'refreshing.customCell' (0x10b2f6dd0).

*refreshing 是项目名称。

bug 的绿线设置为这一行:

let cell:customCell = tableView.dequeueReusableCellWithIdentifier("cell") as! customCell

有什么建议吗?

最佳答案

您正在使用旧的装饰方法,该方法需要您创建单元格或使用采用indexPath的新方法

let cell:customCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath:indexPath) as! customCell

如果仍然失败,您需要注册单元,方法是在 Storyboard 中进行设置,或者在代码中注册类或 nib 文件。

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.registerNib(UINib(nibName: "customCell", bundle: nil), forCellReuseIdentifier: "cell")
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.registerClass(customCell.self, forCellReuseIdentifier: "cell")
}

关于ios - 无法将 UITableViewCell 设置为单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31789588/

相关文章:

ios - 返回闭包外部的变量

ios - 是否可以使用 iOS 11 拖放在 UITableView 中一次重新排序多个项目/单元格?

ios - 如何设置NSTimer的计数限制?

ios - 当表格未处于编辑模式时,我可以使用 UITableViewCellEditingStyleInsert 吗?

swift - 在 Swift 中的 tableview 行之间拆分 JSON 响应的问题

ios - UITabBarController 检查选项卡是否是第一次选择

ios - 具有不同部分和行号的 TableView

ios - 白色标签 iOS 应用程序

ios - 从我的应用程序中过滤照片库的内容

ios - 某些日期的 DateFormatter.localizedString 已损坏