我制作了一个 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/