在Swift 2.0中正确实现cellForRowAtIndexPath

Aru*_*Das 7 uitableview ios swift

以下实现的cellForRowAtIndexPath是技术上正确的最佳实践方式,考虑到可选项的展开

 class MyTableViewController: UITableViewController {
        var cell : UITableViewCell?
         // other methods here 
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        cell = tableView.dequeueReusableCellWithIdentifier("ItemCell")! as UITableViewCell
        let myItem = items[indexPath.row]

        cell!.textLabel?.text = myItem.name
        cell!.detailTextLabel?.text = myItem.addedByUser

        return cell!
      }

    }
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 7

在Swift 2 dequeueReusableCellWithIdentifier中声明为

func dequeueReusableCellWithIdentifier(_ identifier: String,
                      forIndexPath indexPath: NSIndexPath) -> UITableViewCell
Run Code Online (Sandbox Code Playgroud)

并被cellForRowAtIndexPath宣布为

func tableView(tableView: UITableView, 
             cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
Run Code Online (Sandbox Code Playgroud)

你看,没有选择!

代码可以减少到

class MyTableViewController: UITableViewController {

   // other methods here 
   override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath)
     let myItem = items[indexPath.row]

     cell.textLabel?.text = myItem.name
     cell.detailTextLabel?.text = myItem.addedByUser

     return cell
  }
}
Run Code Online (Sandbox Code Playgroud)

如果是自定义表格视图单元格,则可以将单元格强制转换为自定义类型.

let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! CustomCell
Run Code Online (Sandbox Code Playgroud)

选择单击符号或使用"快速帮助"查找确切的签名始终是个好主意.