UITableView单元格错误 Xcode 7 / Swift 2

15

我在这段代码中遇到了以下错误:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell

错误:从“UITableViewCell?”向下转型为“UITableViewCell”仅取消可选项;您是否意味着使用“!”?

有什么想法吗?


UITableViewCell? 更改为 UITableViewCell! - Kendel
6个回答

30
在Swift2.0中,方法dequeueReusableCellWithIdentifier被声明为:
@available(iOS 6.0, *)
func dequeueReusableCellWithIdentifier(identifier: String, forIndexPath indexPath: NSIndexPath) -> UITableViewCell

你不应该将 UITableViewCell 强制转换为 UITableViewCell?。请参见下面的代码。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)

    // Configure the cell...

    return cell
}

希望这有所帮助!

3

从Xcode 7开始,dequeueReusableCellWithIdentifier将始终返回一个非可选的UITableViewCell

您甚至不需要指定类型,可以简洁地编写:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell")

如果您有自定义的UITableViewCell子类

guard let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? SomeOtherCell else { fatalError("unexpected cell dequeued from tableView") }

0
 CMessageCell=self.MessageTable.dequeueReusableCellWithIdentifier("CustomMessageCell") as! CustomMessageCell

0

使用这个代替

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell")

-1

如果你想使用标识符,应该使用这些方法:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 100
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("WHAT-EVER-YOU-WANT-TO-CALL-IT", forIndexPath: indexPath)
    let label = cell.viewWithTag(1000) as! UILabel
}
    return cell 

-2
var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as UITableViewCell!

2
欢迎来到SO!请始终为您的答案提供解释。仅有代码的答案很少有帮助。首先,每个阅读您答案的人都必须弄清楚您想要表达什么(这里只是一个字符的差异),然后我们都必须猜测为什么您提出这个作为解决方案。始终问自己,为什么您的答案比其他已有的答案更好?如果您无法解释,请不要发布。 - cfi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接