我试图从按下的单元格中返回 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/