TableView loads data incorrectly

Asked by At

I am working on a settings page for my app where I use a UITableView. I want two of the cells to have blue text (as shown below in my code). This works fine when I scroll down to check them (as they are not in view when the UIViewController is initially loaded), but when I scroll back up some of my cells have blue text. This same issue is occurring when I try and set text to bold. In addition, when I scroll down again and up again the cells which are blue change (sometimes). Any help regarding this bizarre issue would be much appreciated. My code:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 16
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "settingsCell") as? SettingsTableViewCell

    cell!.setText(name: settingOptions[indexPath.row])
    tableView.rowHeight = 50

    if indexPath.row == 14 || indexPath.row == 15 {
        cell!.setColor(name: settingOptions[indexPath.row])
    }

    return cell!
}

The cell class:

class SettingsTableViewCell: UITableViewCell {

    @IBOutlet weak var title: UILabel!

    func setText(name: String) {
        title.text = name
    }

    func setColor(name: String) {
        title.textColor = UIColor(red: 0.18823, green: 0.54118, blue: 0.9882, alpha: 1.0)
    }
}

0 Answers