I'm new and learning swift
I want to use static cells in my table view. I have all cells look similar so I thought of using xib for tablecell and use that in my static table view.
Problem I'm facing currently is, when I try to access label that i have in xib is throwing me error in method: ConfigureCell in below code. Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value Why is it saying im unwrapping optional when I dont have one
Not sure what needs to be done here/ Please advice.
below is my code:
class NewTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(ReusableTableViewCell.self, forCellReuseIdentifier:"custom")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 4
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "custom", for: indexPath) as? ReusableTableViewCell else {
return UITableViewCell()
}
if indexPath.row == 0 {
cell.configureCell(title: "Name", detail: "hello")
}
if indexPath.row == 2 {
cell.configureCell(title: "Age", detail: "23")
}
if indexPath.row == 3 {
cell.configureCell(title: "Dept", detail: "HR")
}
return cell
}
}
class ReusableTableViewCell: UITableViewCell {
@IBOutlet weak var leftLabel: UILabel!
@IBOutlet weak var rightLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configureCell(title: String, detail: String) {
leftLabel.text = title //Error Here: Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
rightLabel.text = detail
}
Found solution to this. Problem is with line self.tableView.register(ReusableTableViewCell.self, forCellReuseIdentifier:"custom")
Replacing that with tableView.register(UINib(nibName: "ReusableTableViewCell", bundle: nil), forCellReuseIdentifier: "custom") solved the issue
Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.