当前位置:  开发笔记 > IOS > 正文

在Swift 2.0中正确实现cellForRowAtIndexPath

如何解决《在Swift2.0中正确实现cellForRowAtIndexPath》经验,为你挑选了1个好方法。

以下实现的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!
      }

    }

vadian.. 7

在Swift 2 dequeueReusableCellWithIdentifier中声明为

func dequeueReusableCellWithIdentifier(_ identifier: String,
                      forIndexPath indexPath: NSIndexPath) -> UITableViewCell

并被cellForRowAtIndexPath宣布为

func tableView(tableView: UITableView, 
             cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

你看,没有选择!

代码可以减少到

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
  }
}

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

let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! CustomCell

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



1> vadian..:

在Swift 2 dequeueReusableCellWithIdentifier中声明为

func dequeueReusableCellWithIdentifier(_ identifier: String,
                      forIndexPath indexPath: NSIndexPath) -> UITableViewCell

并被cellForRowAtIndexPath宣布为

func tableView(tableView: UITableView, 
             cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

你看,没有选择!

代码可以减少到

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
  }
}

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

let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! CustomCell

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

推荐阅读
mobiledu2402851203
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有