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

nuypyhwy  于 2023-03-28  发布在  Swift
关注(0)|答案(5)|浏览(269)

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

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

但得到编译错误为:
无法将类型“(UITableViewCell).Type”的值转换为指定的类型“UITableViewCell”
同一行上的连续语句必须用“”分隔;”
示例成员“cellForRowAtIndexPath”不能用于类型“UITableView”;你是想用这个类型的值来代替吗?

k10s72fa

k10s72fa1#

cellForRowAtIndexPath不是类方法。请改用示例方法。

let cell = tableView.cellForRowAtIndexPath(indexPath)

雨燕3:

let cell = tableView.cellForRow(at: indexPath)
0tdrvxhp

0tdrvxhp2#

你可以在Swift 4中使用它

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

t2a7ltrp3#

首先得到你想去的行号,然后调用下面的代码。

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

zzwlnbp84#

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!
iovurdzv

iovurdzv5#

为了防止它崩溃,请使用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
}

相关问题