NSUserDefaults 更改后,UITableView 和 UITableViewCell 未更新

UITableView and UITableViewCell did not update after NSUserDefaults change

我正在开发一个应用程序,允许用户更改应用程序主 viewcontroller 上 UITableViewCells 的背景颜色和字体。您可能猜到此更改是在应用程序的设置页面上设置的,当我从设置页面导航回主视图时,更改没有发生。例如,如果 table 视图单元格的背景是蓝色,我将其更改为红色,只有当我在多任务处理中终止应用程序并恢复它或者滚动 table 视图时才会发生。

我现在不知道该怎么做真的这是我的代码,任何建议将不胜感激。

   func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("MensajeUsuario", forIndexPath: indexPath) as! TableViewCell
    cell.selectionStyle = .None
    let mensaje = CoreDatos[indexPath.row]
    cell.textLabel!.text = mensaje.valueForKey("name") as? String
    cell.textLabel?.backgroundColor = UIColor.clearColor()

    cell.delegate = self
    cell.toDoItem = mensaje
    return cell
}


 func colorForIndex(index: Int) -> UIColor {

    var ud: NSUserDefaults = NSUserDefaults.standardUserDefaults()
    var eleccion: Int = ud.integerForKey("Color")
    let itemCount = CoreDatos.count - 1
    let val = (CGFloat(index) / CGFloat(itemCount)) * 0.6
    var esquema = UIColor()


        switch eleccion
        { case 1 : esquema = UIColor(red: val , green: 0.2 , blue: 0.9 , alpha: 1.0)//HeadApp
          case 2 : esquema = UIColor(red: 0.0 , green: val , blue: 1.0 , alpha: 1.0)//Blue
          case 3 : esquema = UIColor(red: 1.0 , green: val , blue: val , alpha: 1.0)//Red
          case 4 : esquema = UIColor(red: val , green: 0.75 , blue: 0.0 , alpha: 1.0)//Green
          case 5 : esquema = UIColor(red: 0.8 , green: val , blue: 0.75 , alpha: 1.0)//Pink
          case 6 : esquema = UIColor(red: 0.5 , green: val , blue: 1.0 , alpha: 1.0)//Violeta
          case 7 : esquema = UIColor(red: 0.9 , green: 0.9 , blue: 0.9 , alpha: 1.0)//White
          default : esquema = UIColor(red: val , green: 0.2 , blue: 0.9 , alpha: 1.0)//HeadApp

        }


    return esquema  }

func tableView(tableView: UITableView, willDisplayCell cell:     UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath) {
        cell.backgroundColor = colorForIndex(indexPath.row)
}

前者是 table 视图的方法,在索引颜色中我使用 NSUserDefaults 来读取用户选择。

我现在不知道调用什么方法来重新加载视图以查看更改。

此时我真的不知道该怎么办,请提供任何帮助,我真的很感激。

您可以拨打

tableView.reloadData()

viewDidAppear

您的 tableview 没有更新的原因是它处于您在 viewDidLoad 中设置的相同状态。更改设置后,它仍然保持不变,因为从设置导航回来时不会再次调用 viewDidLoad。尽管从设置返回时将调用 viewDidAppear。

if i kill the app on multitasking and restore it or if i scroll the table view.

终止应用程序将再次调用 viewDidLoad 并加载最新值。 滚动也会加载单元格中的最新数据,因为

cellForRowAtIndexPath

将被调用并加载更新值。