首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >NSIndexPath?在Swift中没有成员名称'row‘错误

NSIndexPath?在Swift中没有成员名称'row‘错误
EN

Stack Overflow用户
提问于 2014-06-04 22:36:23
回答 4查看 16.1K关注 0票数 20

我正在用Swift语言和一个方法创建一个UITableViewController

代码语言:javascript
复制
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell?

我得到了这个错误

NSIndexPath?在Swift中没有成员名称'row‘错误

我不明白为什么。

这是我的代码

代码语言:javascript
复制
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呢?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-06-04 22:47:14

您可以使用if let...解包可选的indexPath参数

代码语言:javascript
复制
if let row = indexPath?.row {
    cell.textLabel.text = self.dataStore[row]
}

或者,如果您确定indexPath不是nil,您可以使用!强制解包

代码语言:javascript
复制
cell.textLabel.text = self.dataStore[indexPath!.row]

请记住,nil值的indexPath!将是一个运行时异常,因此更好的做法是像第一个示例那样解开它。

票数 15
EN

Stack Overflow用户

发布于 2014-06-04 22:57:39

您可以对此调用使用可选的链接语法(如果indexPathnil,则将cell.textLabel.text设置为nil ):

代码语言:javascript
复制
cell.textLabel.text = indexPath? ? self.dataStore[indexPath!.row] : nil

或者显式地解开它(如果indexPath为nil,则会导致运行时错误):

代码语言:javascript
复制
cell.textLabel.text = self.dataStore[indexPath!.row]

或者使用@NateCook建议的更详细的if let语法。

票数 5
EN

Stack Overflow用户

发布于 2018-08-22 15:06:33

使用.item而不是.row

cell.textLabel.text = self.dataStore[indexPath.item]

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24040405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档