Search code examples
iosswiftuitableviewviewwithtag

Everytime I scroll cell.viewWithTag will give fatal error while unwrapping found nil


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        
  ...
 }

Solution

  • I fixed the problem by adding this if-clause:

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