0

I have a table view with cells everytime I scroll I get fatal error: unexpectedly found nil while unwrapping an Optional value

And it wil mark this code green: let button = cell.viewWithTag(1009) as! UIButton

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 
  let cell = tableView.dequeueReusableCellWithIdentifier("ChecklistItem") as! UITableViewCell 
  let label = cell.viewWithTag(1000) as! UILabel 
  let button = cell.viewWithTag(1009) as! UIButton 
  button.tag = indexPath.row        
  ...
 }
Mrunal
  • 13,474
  • 6
  • 48
  • 91
  • Please add your `cellForRowAtIndexPath` method code along with question body, for better understanding. – Mrunal Jul 30 '15 at 09:04
  • `override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ChecklistItem") as! UITableViewCell let label = cell.viewWithTag(1000) as! UILabel let button = cell.viewWithTag(1009) as! UIButton button.tag = indexPath.row` –  Jul 30 '15 at 09:05
  • Doesn't solve the problem, I already had the brackets and also a return statement. This is just the same... –  Jul 30 '15 at 09:17
  • 1
    Then in your case, I would suggest to use custom cell class rather dealing with tag values. Reference: http://stackoverflow.com/questions/24170922/creating-custom-tableview-cells-in-swift – Mrunal Jul 30 '15 at 09:22

2 Answers2

0

I fixed the problem by adding this if-clause:

  if button == nil{
        println("Do nothing");
    }else{
        button!.tag = indexPath.row

    }
0

get fatal error: unexpectedly found nil while unwrapping an Optional value caused you get button from viewWithTag after you set tag

let button = cell.viewWithTag(1009) as! UIButton 
**button.tag = indexPath.row**

So did not updated button tag, pass required information in button accessibilityIdentifier

let button = cell.viewWithTag(1009) as! UIButton 
button.accessibilityIdentifier = "\(indexPath.row)"

after Get button information by

let indexRow = Int(button.accessibilityIdentifier!)
Shaheen
  • 131
  • 1
  • 4