Reputation: 191
I want to access cell of tableView from outside tableView func, for example in this case I want to access from a IBAction Func, then I have created tableView object and IndexPath object, when I running my project the Xcode shows me this error:
Fatal error: unexpectedly found nil while unwrapping an Optional values
for this line: mytableView!.cellForRowAtIndexPath(indexPath!)
@IBAction func editButtonFunc(sender: AnyObject) {
mytableView!.cellForRowAtIndexPath(indexPath!)
let cell =
mytableView!.dequeueReusableCellWithIdentifier(
"mycell", forIndexPath: indexPath!)
as! profileTableViewCell
cell.contentOutlet.text = contentItems[indexPath!.row]
cell.contentOutlet.textAlignment = NSTextAlignment.Right
cell.contentOutlet.font = UIFont(name: "X Yekan", size: 18)
}
Upvotes: 1
Views: 307
Reputation: 52538
Calling the tableview method cellForRowAtIndexPath is almost always wrong. It will return nil if the index path is not for a cell that is visible on the screen. Your case is worse because you call the function and then don't use its value. What is absolutely, totally wrong is calling dequeue.... from anywhere other than your own delegate cellForRowAtIndexPath.
Upvotes: 0
Reputation: 38142
Clearly either mytableView
or indexPath
is nil
when you are trying to unwrap it. You must check both these objects holds right value before you force unwrap them.
Upvotes: 0
Reputation: 2190
If you just want to get the ref of some cell, perhaps you need:
func getTableViewCell() -> UITableViewCell? {
guard let tableView = mytableView, index = indexPath
else { return nil }
return tableView.cellForRowAtIndexPath(index)
}
And, If you want to set data for the tableViewCell, you should do this in the UITableViewDataSource
methods: cellForRowAtIndexPath
.
Upvotes: 0