UITableVIewCell 错误 Xcode 7 / Swift 2

Posted

技术标签:

【中文标题】UITableVIewCell 错误 Xcode 7 / Swift 2【英文标题】:UITableVIewCell Error Xcode 7 / Swift 2 【发布时间】:2015-08-02 17:09:26 【问题描述】:

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

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

错误:从“UITableViewCell”向下转换?到 'UITableViewCell' 只解开选项;您的意思是使用“!”吗?

有什么想法吗?

【问题讨论】:

UITableViewCell? 更改为UITableViewCell! 【参考方案1】:

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

希望这会有所帮助!

【讨论】:

【参考方案2】:

从 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") 

【讨论】:

【参考方案3】:

改用这个

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

【讨论】:

【参考方案4】:
 CMessageCell=self.MessageTable.dequeueReusableCellWithIdentifier("CustomMessageCell") as! CustomMessageCell

【讨论】:

【参考方案5】:

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

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 

【讨论】:

【参考方案6】:
var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as UITableViewCell!

【讨论】:

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

以上是关于UITableVIewCell 错误 Xcode 7 / Swift 2的主要内容,如果未能解决你的问题,请参考以下文章

自定义 UITableViewCell 高度宽度提供了错误的值。

静态 UITableViewCell 中的 UISwitch 生成错误

使用 xcode 6 为 uitableviewcell 自动布局

UITableViewCell Autolayout问题(iOS 11,Xcode 9.2)

如何在 xcode 中设置 UITableViewCell 标识符?

使用 Xcode 7 自定义 UITableViewCell 和 UITextfield