1
votes

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)

}
3
Where do you create the indexPath?joern
You shouldn't dequeue a cell in this method. If cellForRowAtIndexPath returns nil then no cell is currently available for that index path and you should just move on.Paulw11

3 Answers

0
votes

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.

0
votes

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.

0
votes

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.