Swift 中的 UITableView

标签 uitableview swift ios8

我正在努力弄清楚这段代码有什么问题。这目前在 Objective-C 中有效,但在 Swift 中,这只会在方法的第一行崩溃。它在控制台日志中显示一条错误消息:Bad_Instruction

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

        if (cell == nil) {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
        }

        cell.textLabel.text = "TEXT"
        cell.detailTextLabel.text = "DETAIL TEXT"

        return cell
    }

最佳答案

另见 matt's answer其中包含解决方案的后半部分

让我们在不创建自定义子类或 nib 的情况下找到解决方案

真正的问题在于 Swift 区分可以为空的对象 (nil) 和不能为空的对象。如果您没有为您的标识符注册一个 nib,那么 dequeueReusableCellWithIdentifier 可以返回 nil

这意味着我们必须将变量声明为可选:

var cell : UITableViewCell?

而且我们必须使用 as? 而不是 as

//variable type is inferred
var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell

if cell == nil {
    cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
}

// we know that cell is not empty now so we use ! to force unwrapping but you could also define cell as
// let cell = (tableView.dequeue... as? UITableViewCell) ?? UITableViewCell(style: ...)

cell!.textLabel.text = "Baking Soda"
cell!.detailTextLabel.text = "1/2 cup"

cell!.textLabel.text = "Hello World"

return cell

关于Swift 中的 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24022763/

相关文章:

ios - 无法使用带有 NSLocationWhenInUseUsageDescription 的 Swift 和 iOS8 获取位置服务

swift - 照片编辑扩展问题 (iOS 8)

swift - 无法更改 TableView 中标签的文本

ios - heightForRowatIndexPath 不设置单元格高度

ios - NSInternalInconsistencyException : must register a nib or a class for the identifier or connect a prototype cell in a storyboard

swift - 当用户单击一个按钮时,当他们靠近某个位置时会获得 x 点 (SWIFT)

ios - 使用 Swift 更新 Firebase 中的子值

iphone - 在表格 View 单元格上绘制一条线并将其移动到表格末尾时的 UITableview 可重用性问题

ios - 一旦我从分享扩展分享到我的应用程序的链接,Safari 就会被卡住

ios - 如何导出在设备中为 Xcode 6 创建的文件?