Tableview равен нулю при перезагрузке данных - PullRequest
1 голос
/ 23 апреля 2020

Итак, у меня есть табличное представление с двумя ячейками. Одним из них является тумблер, который при отключении меняет цвет текста во второй ячейке на серый. Я обрабатываю переключатель для этой ячейки в ее пользовательском классе ячеек и устанавливаю логическое значение для него в классе таблицы, используя didSet, чтобы вызвать функцию для перезагрузки табличного представления. Проблема в том, что табличное представление, которое я связал с раскадровкой, равно нулю, когда оно перезагружает данные, но только когда функция вызывается из didSet. Когда он вызывается нормально с помощью других средств, таких как viewDidLoad(), он работает как положено. Полная ошибка: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

    class Notifications: UIViewController {

    var notificationsEnabled:Bool = true {
        didSet {
            RefreshTable()
        }
    }

    @IBOutlet weak var notificationsTableView: RoundedTable!

    var notificationItems = ["Notifications", "Time"]

    override func viewDidLoad() {
        super.viewDidLoad()
        notificationsTableView!.dataSource = self
        notificationsTableView!.delegate = self
    }

    func RefreshTable() {
        notificationsTableView.reloadData() //Crashes here
    }
}

extension Notifications: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {  
        switch indexPath.row {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "notificationToggleCell", for: indexPath) as! NotificationToggleCell
            cell.notificationToggleLbl.text = notificationItems[indexPath.row]
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: "notificationTimeCell", for: indexPath) as! NotificationTimeCell
            cell.notificationTimeLbl.text = notificationItems[indexPath.row]
            if (!notificationsEnabled) {
                cell.notificationTimeLbl.textColor = .gray
                cell.notificationTimeTxt.textColor = .gray
            }
            return cell
        default:
            return UITableViewCell()
        }
    }
}

А вот пользовательский класс ячейки:

class NotificationToggleCell: UITableViewCell {

    @IBOutlet weak var notificationToggleLbl: UILabel!
    @IBOutlet weak var notificationToggleSwitch: UISwitch!

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    @IBAction func notificationSwitchChanged(_ sender: Any) {
        let notificationsViewController = storyboard.instantiateViewController(withIdentifier: "Notifications") as! Notifications
        if (notificationToggleSwitch.isOn) {
            notificationsViewController.notificationsEnabled = true
        }
        if (!notificationToggleSwitch.isOn) {
            notificationsViewController.notificationsEnabled = false
        }
    }
}

1 Ответ

2 голосов
/ 23 апреля 2020

Попробуйте использовать шаблон проектирования делегата.

protocol NotificationsDelegate {
    func toggleSwitched()
}

В свой NotificationToggleCell добавьте

var toggleDelegate: NotificationsDelegate?

@objc func toggleSwitched() {
    toggleDelegate.toggleSwitched()
}

В функцию cellForRowAt

cell. toggleDelegate = self

и, наконец,

extension Notifications: NotificationsDelegate { 
    func toggleSwitched() {
        RefreshTable()
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...