Reputation: 858
I'm trying to get UITableViewCell object programmatically using Swift, so I wrote this code:
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?
Upvotes: 49
Views: 95188
Reputation: 1198
To prevent it from getting crashed use if let
condition as follows...
if let cell = myTableView.cellForRow(at: IndexPath(row: index, section: 0)) as? MyTableCell {
// do stuff here
cell.updateValues(someValues)
}
also can fetch headerView as follows...
if let headerView = myTableView.headerView(forSection: 0) as? MyHeaderView {
//do something
}
Upvotes: 1
Reputation: 6041
Swift 5 Easy solution
//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!
Upvotes: 7
Reputation: 445
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)
Upvotes: 6
Reputation: 1783
You can use this for Swift 4
let indexPath = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPath)
Upvotes: 41
Reputation: 80271
cellForRowAtIndexPath
is not a class method. Use the instance method instead.
let cell = tableView.cellForRowAtIndexPath(indexPath)
Swift 3:
let cell = tableView.cellForRow(at: indexPath)
Upvotes: 122