繁体   English   中英

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

[英]How to get UITableViewCell object from indexPath in Swift?

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

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

但得到编译错误为:

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

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

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)

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!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM