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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25094732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:39:27  来源:igfitidea点击:

How to get UITableViewCell object from indexPath in Swift?

iosuitableviewswift

提问by shripad20

I'm trying to get UITableViewCell object programmatically using Swift, so I wrote this code:

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

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

but getting compile error as:

但得到编译错误为:

Cannot convert value of type '(UITableViewCell).Type' to specified type 'UITableViewCell'
Consecutive statements on a line must be separated by ';'
Instance member 'cellForRowAtIndexPath' cannot be used on type 'UITableView'; did you mean to use a value of this type instead?

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

回答by Mundi

cellForRowAtIndexPathis not a class method. Use the instance method instead.

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

let cell = tableView.cellForRowAtIndexPath(indexPath)

Swift 3:

斯威夫特 3:

let cell = tableView.cellForRow(at: indexPath)

回答by Celil Bozkurt

You can use this for Swift 4

您可以将其用于Swift 4

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

回答by Ali Aqdas

First get row number where you want to go then call below code.

首先获取您想要去的行号,然后调用下面的代码。

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

回答by Shakeel Ahmed

Swift 5 Easy solution

Swift 5 简易解决方案

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

Table View

表格视图

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

Usage

用法

let tempImage = cell.yourImageView.image!