dpb*_*ler 20 uitableview ios swift
我正在使用Swift语言和方法创建一个UITableViewController
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell?
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误
NSIndexPath?在Swift中没有成员名称'row'错误
而且我不明白为什么.
这是我的代码
import UIKit
class DPBPlainTableViewController: UITableViewController {
var dataStore: NSArray = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
self.dataStore = ["one","two","three"]
println(self.dataStore)
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return self.dataStore.count
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel.text = self.dataStore[indexPath.row]
return cell
}
}
Run Code Online (Sandbox Code Playgroud)
那么,如何使用数组dataStore元素设置cell.text?
Nat*_*ook 15
您可以使用以下命令解包可选indexPath参数if let...:
if let row = indexPath?.row {
cell.textLabel.text = self.dataStore[row]
}
Run Code Online (Sandbox Code Playgroud)
或者如果您确定indexPath不是nil,您可以强制解包!:
cell.textLabel.text = self.dataStore[indexPath!.row]
Run Code Online (Sandbox Code Playgroud)
请记住,indexPath!在nil值上将是运行时异常,因此最好在第一个示例中解开它.
您可以使用可选的链接语法此调用(设置cell.textLabel.text到nil如果indexPath是nil):
cell.textLabel.text = indexPath? ? self.dataStore[indexPath!.row] : nil
Run Code Online (Sandbox Code Playgroud)
或显式解包(如果indexPath导致运行时错误nil):
cell.textLabel.text = self.dataStore[indexPath!.row]
Run Code Online (Sandbox Code Playgroud)
或者使用if let@NateCook建议的更详细的语法.
| 归档时间: |
|
| 查看次数: |
15767 次 |
| 最近记录: |