NSIndexPath? 在Swift中没有成员名“行”错误
我正在用Swift语言和方法创build一个UITableViewController
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell?
我得到这个错误
NSIndexPath? 在Swift中没有成员名“行”错误
我不明白为什么。
这是我的代码
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 } }
那么,如何设置cell.text与数组dataStore元素?
你可以打开可选的indexPath
参数, if let...
:
if let row = indexPath?.row { cell.textLabel.text = self.dataStore[row] }
或者如果你确定indexPath
不是nil
,你可以强制解包!
:
cell.textLabel.text = self.dataStore[indexPath!.row]
请记住, indexPath!
在一个零值将是一个运行时exception,所以最好的做法是解开它,如第一个例子。
你可以在这个调用中使用可选的链接语法(如果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
语法。
所有你需要做的访问NSIndexPath
的行和部分是导入文件的头文件,这些扩展到基本的NSIndexPath
类被定义。
如果你不这样做,你的类将像行和部分一样行事,就是不存在于NSIndexPath
一个实例上。
NSIndexPath
的行和段扩展在UITableView.h
的UIKit框架内声明。
要解决这个问题,你需要做的就是将UITableView.h
导入到你的类中。 而已。
Objective-C中的UITableView.h中定义了类的扩展。 我相信Swift有一个类似的部分。
// This category provides convenience methods to make it easier to use an NSIndexPath to represent a section and row @interface NSIndexPath (UITableView) + (instancetype)indexPathForRow:(NSInteger)row inSection:(NSInteger)section; @property (nonatomic, readonly) NSInteger section; @property (nonatomic, readonly) NSInteger row; @end
- Png的iOS – png的捆绑vs下载 – png8 vs png24
- 在WKWebView中允许未经validation的SSL证书
- 如何从JSON输出数据解码路由点?
- 如何判断(编程)是否有任何注册的应用程序支持打开特定的文档types?
- MPMoviePlayerController从30秒开始播放video(从video中间开始)
- UITextView专注,但用户触摸UICollectionViewCell。 隐藏键盘并运行didSelectItemAtIndexPath
- iOS 11密码自动填充
- 如何在UIButton中实现两个IBActions而不重叠?
- 如果我重写一个类的方法,有没有办法,我可以调用原来的方法(被覆盖的方法)?