ios - 在 Swift 2.0 中定义 'UITableViewCell' 变量

标签 ios swift uitableview

我正在尝试使用 swift 创建 UITableViewCell 类型变量,这些是我的代码:

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dwarves.count
    }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier)! as UITableViewCell if (cell == nil) { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: simpleTableIdentifier) } cell.textLabel?.text = dwarves[indexPath.row] return cell }

在第 7 行 if (cell == nil),它给我一个错误,即 Value of type 'UITableViewCell' can never be nil, comparation isn't allowed . 不能用 if ( !cell ) 代替。我应该如何修复代码?

最佳答案

如果你真的想使用过时的方法 tableView.dequeueReusableCellWithIdentifier(_:) 你可以这样做:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) ?? UITableViewCell(style: .Default, reuseIdentifier: simpleTableIdentifier)
    cell.textLabel?.text = dwarves[indexPath.row]

    return cell
}

但是你最好使用dequeueReusableCellWithIdentifier(_:forIndexPath:)它永远不会返回 nil
它与 registerClass(_:forCellReuseIdentifier:) 一起使用和 registerNib(_:forCellReuseIdentifier:) .

关于ios - 在 Swift 2.0 中定义 'UITableViewCell' 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34203044/

相关文章:

ios - 在 AppDelegate 中实例化 UITableViewController 以与 Storyboard iOS 配合使用

ios - 如何从暂停点恢复 HLS 直播?

ios - 如何在 iOS 中点击缩放和双击缩小?

swift - 使用绑定(bind)的 Cocoa 文本标签上的 "disabled"样式

ios - uidevicebatterystatedidchangenotification 有时不工作

ios - 从 SWRevealViewController 中存在的 tableview 单元格展开 segue

iphone - 快速删除存储在 NSArray 中的几个 managedObjectContext

ios - UIApplicationSignificantTimeChange 通知未触发

iOS - UITableViewCell 图像调整/调整大小

swift - 使用存储在 Firebase 数据库中的数据填充 UITableView