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



我试图获得UITableViewCell对象编程使用Swift,所以我写了这个代码:

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

但编译错误为:

不能转换类型'(UITableViewCell)的值。将'类型'指定为'UITableViewCell'
一行中连续的语句必须用';'分隔
实例成员'cellForRowAtIndexPath'不能用于类型'UITableView';您的意思是使用这种类型的值吗?

cellForRowAtIndexPath不是一个类方法。使用instance方法代替。

let cell = tableView.cellForRowAtIndexPath(indexPath)

迅速3:

let cell = tableView.cellForRow(at: indexPath)

Swift 4

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

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

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

快速解决方案

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

表视图

let cell = tableView.cellForRow(at: indexPath) as! YourTableViewCell
使用

let tempImage = cell.yourImageView.image!

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

最新更新