在Swift中如何从indexPath获取UITableViewCell对象?

49

我正在尝试使用Swift编程以编程方式获取UITableViewCell对象,因此编写了以下代码:

let cell:UITableViewCell = (UITableViewCell) UITableView.cellForRowAtIndexPath(indexPath.row)

但是遇到了编译错误:

无法将类型“(UITableViewCell).Type”的值转换为指定类型“UITableViewCell”
一行上的连续语句必须用“;”隔开
实例成员“cellForRowAtIndexPath”无法用于类型“UITableView”;是否意图使用该类型的值?


请参考以下问题,可能与此重复:https://dev59.com/SWw15IYBdhLWcg3wisW- - Akash S
5个回答

121

cellForRowAtIndexPath不是类方法。请使用实例方法。

let cell = tableView.cellForRowAtIndexPath(indexPath)

Swift 3:

let cell = tableView.cellForRow(at: indexPath)

6
cellForRowAtIndexPath方法确实需要一个索引路径作为参数。 - Martin R
我在上面的代码中遇到了访问错误。我在这里使用自定义单元格。 - Alok
2
明白了。实际上,heightForRowAtIndexPath在cellForRowAtIndexPath之前被调用,这就是为什么我遇到问题的原因。 - Alok
有没有办法在拥有两个自定义单元格的情况下获取UITableViewCell类型?我需要知道此索引路径返回哪种类型的单元格。获取类型的最佳方法是什么? - user3976000
在Swift中有一个运算符is,用于检查类型,例如cell is CustomCell - Mundi
显示剩余2条评论

41

您可以在 Swift 4 中使用此内容。

let indexPath = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPath)

6

首先获取你想要前往的行号,然后调用以下代码。

let indexPath = IndexPath(row: rowNumber, section: 0)
let tableViewCell = YourTableView.cellForRow(at: indexPath)

4
请不要仅仅发布代码作为答案,而要包含一个解释,说明您的代码是如何解决问题的。有解释的答案通常质量更高,并且更有可能吸引赞同。 - Mark Rotteveel

6

Swift 5简易解决方案

//MARK:- Collection View
let cell = yourcollectionview.cellForItem(at: indexPath) as! YourCollectionViewCell

表格视图
let cell = tableView.cellForRow(at: indexPath) as! YourTableViewCell

使用方法

let tempImage = cell.yourImageView.image!

1
为防止程序崩溃,请使用以下的if let条件语句...
 if let cell = myTableView.cellForRow(at: IndexPath(row: index, section: 0)) as? MyTableCell {
         // do stuff here
     cell.updateValues(someValues)
 }

还可以按以下方式获取headerView...

if let headerView = myTableView.headerView(forSection: 0) as? MyHeaderView {
//do something
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接