我有一个表格视图,里面有两个单元格。其中一个是一个切换开关,当它被禁用时,第二个单元格中的文本颜色就会变成灰色。我在自定义单元格类中处理该单元格的开关,并在表的类中用 didSet
来触发一个函数来重载tableview。问题是,我链接到storyboard的tableview在重载数据到它的时候是nil,但只有在调用函数从 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
}
}
}
尝试使用委托设计模式。
protocol NotificationsDelegate {
func toggleSwitched()
}
在你的NotificationToggleCell中添加以下内容
var toggleDelegate: NotificationsDelegate?
@objc func toggleSwitched() {
toggleDelegate.toggleSwitched()
}
在cellForRowAt函数中
cell. toggleDelegate = self
最后
extension Notifications: NotificationsDelegate {
func toggleSwitched() {
RefreshTable()
}
}