UITableVIewCell 错误 Xcode 7 / Swift 2

UITableVIewCell Error Xcode 7 / Swift 2

我运行在这段代码中出现以下错误:

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

错误:从 'UITableViewCell?' 向下转换为 'UITableViewCell' 仅解包选项;您是要使用“!”吗?

有什么想法吗?

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
}

希望对您有所帮助!

改用这个

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

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

你甚至不需要指定类型,它可以简洁地写成:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell")

或者如果您有 UITableViewCell

的自定义子类
guard let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? SomeOtherCell else { fatalError("unexpected cell dequeued from tableView") }

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

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 
 CMessageCell=self.MessageTable.dequeueReusableCellWithIdentifier("CustomMessageCell") as! CustomMessageCell