arsipups
arsipups

Reputation: 1

iOS App UILabel crashed when I change text size from iOS Settings Screen

I have

@IBOutlet weak var onlineStatusLabel: UILabel! 

declared in TableViewCell Class My table view use static cells. When I inside the app everything is ok, once I change text size setting in iOS setting screen and come back to my app, app crashes with this error:

appName/TableVC.swift:47: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

This is what I call from my TableVC:

import UIKit

class TableVC: UITableViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
      //  super.tableView(tableView, willDisplay: cell, forRowAt: indexPath)
        guard let cell = cell as? CustomTableViewCell else { return }
        cell.onlineStatusLabel.textColor = .red // app crash here, this means that onlineStatusLabel is nil, but how???
        cell.onlineStatusLabel.text = "Text"
    }
}

CellView:

import UIKit

class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var onlineStatusLabel: 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
    }

}

Image with code for TableVC

Image with code for Cell

Storyboard configuration

Storyboard cell configuration

How it can be nil? How size change can react on UILabel? Can you please suggest?

Upvotes: 0

Views: 284

Answers (1)

THEJAS
THEJAS

Reputation: 111

I would suggest writing one method within cell class like this

public func setupLabel() {
    
    guard onlineStatusLabel != nil else {return}
    
    self.onlineStatusLabel.textColor = .red
    self.onlineStatusLabel.text = "Text"
}

And call that function with table view delegate method like this

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    //  super.tableView(tableView, willDisplay: cell, forRowAt: indexPath)
    guard let cell = cell as? CustomTableViewCell else { return }
    cell.setupLabel()
}

Upvotes: 0

Related Questions