0

xcode: 9.4.1

I'm creating a simple table view but I keep getting the same "Unexpectedly found nil while unwrapping an Optional value" error when it comes to set a value to a component in each cell.

import UIKit class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var conditionTable: UITableView! var conditions = [Condition]() override func viewDidLoad() { super.viewDidLoad() conditionTable.register(ConditionCell.self, forCellReuseIdentifier: "conditionCell") conditionTable.delegate = self conditionTable.dataSource = self setInitData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setInitData() { conditions.append(Condition(name: "a")) conditions.append(Condition(name: "b")) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return conditions.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell: ConditionCell = tableView.dequeueReusableCell(withIdentifier: "conditionCell") as? ConditionCell else { fatalError() } print(cell.conditionLabel.text) // cell.setCell(condition: conditions[indexPath.row]) return cell } } 

I did name my custom cell "ConditionCell" and I did name the identified "conditionCell".

Here is my custom cell class. I did add the component(label) reference to the class. It looks like the custom view class is successfully loaded (not nil) however its component (label) is not.

import UIKit class ConditionCell: UITableViewCell { @IBOutlet weak var conditionLabel: UILabel! func setCell(condition: Condition) { print(conditionLabel) conditionLabel.text = condition.name } } 
4
  • Is the outlet connected to a label in the storyboard? Commented Jul 27, 2018 at 6:21
  • refer to this for creating custom cells: stackoverflow.com/questions/40275727/… Commented Jul 27, 2018 at 6:26
  • 3
    If the cell is designed in Interface Builder you must not register the cell. And remove the guard ... fatalError(). Force unwrap the cell type. If it works once it works forever. And don't name methods with leading set.... Commented Jul 27, 2018 at 6:27
  • Removing the registering part did solve the problem. Thank you so much! Commented Jul 27, 2018 at 6:34

1 Answer 1

1

The problem is with this line :

conditionTable.register(ConditionCell.self, forCellReuseIdentifier: "conditionCell") 

It requires UINib. Change it to:

conditionTable.register(UINib(nibName: "ConditionCell", bundle: nil), forCellReuseIdentifier: "conditionCell") 

For more details check this :

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.