以下实现的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
选择单击符号或使用"快速帮助"查找确切的签名始终是个好主意.
在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
选择单击符号或使用"快速帮助"查找确切的签名始终是个好主意.