ios - didselectrowatindexpath 文本标签返回

标签 ios swift uitableview

我试图从按下的单元格中返回 titleField 或标题值。经过一番挖掘后,我发现了一些应该可以工作的代码,但我得到了错误:

Value of type 'UITableViewCell' has no member 'titleField'

这对于所有其他项目(如标题、标签等)也是相同的。

extension SearchViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return posts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier:"searchCell", for: indexPath)
        as! CustomTableViewCell
        cell.titleField?.text = posts[indexPath.row].caption
        cell.descriptionField?.text = posts[indexPath.row].description
        cell.tagsField?.text = posts[indexPath.row].tags
        let photoUrl = posts[indexPath.row].photoUrl
        let url = URL(string: photoUrl)
        cell.SearchImage.sd_setImage(with: url, placeholderImage: nil)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let indexPath = tableView.indexPathForSelectedRow

        //getting the current cell from the index path
        let currentCell = tableView.cellForRow(at: indexPath!)! as UITableViewCell

        //getting the text of that cell
        let currentItem = currentCell.titleField!.text //HERE IS THE ERROR!
    }
}

最佳答案

切勿使用单元格获取数据。就像在 cellForRowAt 中一样,从数据模型中获取数据。

didSelectRowAt提供了刚刚选中的行的索引路径。

将您的 didSelectRowAt 更新为类似以下内容:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let caption = posts[indexPath.row].caption
    let tags = posts[indexPath.row].tags
}

关于ios - didselectrowatindexpath 文本标签返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50607824/

相关文章:

ios - Swift 在递归函数中不返回正确的值

ios - 像 TodoMovies 3 一样的视差滚动效果

ios - UITableView reloadData 阻塞 UI,每秒更新很多

ios - 静态 UITableViewCell 中的 UISegmentedControl

iphone - cocos2d如何根据不同的iOS设备加载不同的图片?

android - 在 inappbrowser Phonegap webview 应用程序顶部显示自定义导航

ios - 我无法在 iTunes 中显示我的应用程序图标

swift - 如何使用通用默认参数

ios - 如何在 Swift 中覆盖和使用 alloc?

android - cocos2d-x 游戏的最小应用大小是多少?