我正在用Swift语言和一个方法创建一个UITableViewController
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell?
我得到了这个错误
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
}
}
那么,如何使用数组dataStore元素设置cell.text呢?
发布于 2014-06-04 22:47:14
您可以使用if let...
解包可选的indexPath
参数
if let row = indexPath?.row {
cell.textLabel.text = self.dataStore[row]
}
或者,如果您确定indexPath
不是nil
,您可以使用!
强制解包
cell.textLabel.text = self.dataStore[indexPath!.row]
请记住,nil值的indexPath!
将是一个运行时异常,因此更好的做法是像第一个示例那样解开它。
发布于 2014-06-04 22:57:39
您可以对此调用使用可选的链接语法(如果indexPath
为nil
,则将cell.textLabel.text设置为nil
):
cell.textLabel.text = indexPath? ? self.dataStore[indexPath!.row] : nil
或者显式地解开它(如果indexPath为nil
,则会导致运行时错误):
cell.textLabel.text = self.dataStore[indexPath!.row]
或者使用@NateCook建议的更详细的if let
语法。
发布于 2018-08-22 15:06:33
使用.item而不是.row
cell.textLabel.text = self.dataStore[indexPath.item]
https://stackoverflow.com/questions/24040405
复制相似问题