简体   繁体   English

在Swift中从表视图中删除单元格后设置正确的uibutton状态

[英]set correct uibutton state after deleting cell from tableview in Swift

I'm new to Swift and it's quite hard for me to wrap my head around this particular problem. 我是Swift的新手,对于这个特殊的问题,我很难下定决心。 So please be a little patient, if I cannot communicate the point right away. 因此,如果我无法立即传达要点,请耐心等待。 ;-) Thx! ;-) 谢谢!

Basically I have a kind of To-Do-List in a UITable. 基本上,我在UITable中有一种待办事项列表。 The cells have a UIButtons (with a custom class) as a "checkbox". 单元格具有一个UIButtons(带有自定义类)作为“复选框”。 I store the button state in a Dictionary like so: 我将按钮状态存储在Dictionary中,如下所示:

var buttonState = [listItem1 : true, listItem2 : false, ...]

The Dictionary is also stored to NSUserDefaults . 字典也存储到NSUserDefaults This is all working fine. 一切正常。 My problem is, that when I delete cells with the UITableViewCellEditingStyle.Delete function and reload the table after with self.tableView.reloadData() , the button states come up wrong. 我的问题是,当我使用UITableViewCellEditingStyle.Delete函数删除单元格并使用self.tableView.reloadData()之后重新加载表时,按钮状态出现错误。 In the above example, if i deleted listitem1, listItem2 will be displayed as true. 在上面的示例中,如果我删除了listitem1,则listItem2将显示为true。 In fact the stored value is still false. 实际上,存储的值仍然为假。 I guess this must have something to do with the indexPath. 我想这一定与indexPath有关。

Note: I do update the Dictionary before self.tableView.reloadData() to buttonState[listItem1] = nil . 注意:在self.tableView.reloadData()之前,我确实将Dictionary更新为buttonState[listItem1] = nil Meaning I do have the correct value for each ListItem in the dictionary. 意思是我对于字典中的每个ListItem都有正确的值。 Also if I reload the view completely (ie go back one screen in the simulator and reload the list from scratch) all button states come up right. 同样,如果我完全重新加载视图(即在模拟器中返回一个屏幕并从头开始重新加载列表),则所有按钮状态都会正确显示。

How can I get the right button state right after deleting a tablecell without reloading the whole screen? 删除表格单元格后如何在不重新加载整个屏幕的情况下立即获得正确的按钮状态?

Hope all of this makes sense somehow! 希望所有这些都以某种方式有意义! ;-) ;-)

//Seb // Seb

The relevant code in the UITableView: UITableView中的相关代码:

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellItem", forIndexPath: indexPath) as customCell

    //Identify Button with Tag
    cell.checkbox.tag = indexPath.row

    // Set Label
    switch indexPath.section{
    case 0:
        cell.textLabel?.text = "\(kleidung[indexPath.row])"
    case 1:
        cell.textLabel?.text = "\(hygiene[indexPath.row])"
    default:
        cell.textLabel?.text = nil
    }
    // Set Cell State
    cell.onLoadSet()
    return cell
}


// DELETE TABLE ROW
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){

    if (editingStyle == UITableViewCellEditingStyle.Delete){

        if (indexPath.section == 0) {
            kleidung.removeAtIndex(indexPath.row)
            let fixedPackItems = ",".join(kleidung)
            packlisten![rowCount].setValue("\(fixedPackItems)", forKey: "kleidung")
        } else if (indexPath.section == 1) {
            hygiene.removeAtIndex(indexPath.row)
            let fixedPackItems = ",".join(hygiene)
            packlisten![rowCount].setValue("\(fixedPackItems)", forKey: "hygiene")
        }
        context.save(nil)

        if var storedToDoItems: AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey("packItems") {
            var itemString = storedToDoItems as? Dictionary<String, Bool>
            state = itemString!
            println(itemString)
        }

        let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!
        identifier = "\(currentCell.textLabel!.text!)\(rowCount)"
        state[identifier] = nil
        println(state)
        let checkedItems = state as Dictionary
        NSUserDefaults.standardUserDefaults().setObject(checkedItems, forKey: "packItems")
        NSUserDefaults.standardUserDefaults().synchronize()

        self.packlisteTable.reloadData()

    }
}

And in the customCell class: 在customCell类中:

@IBAction func checkboxButton(sender: CheckBox) {

    // Change Button State
    if sender.isChecked == true {
        sender.isChecked = false
    }else{
        sender.isChecked = true
    }

    //Retrieve stored state
    if var storedToDoItems: AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey("packItems") {
        var itemString = storedToDoItems as? Dictionary<String, Bool>
        if itemString != nil {
            state = itemString!
        }
    }

    //Add new State to Stored
    identifier = "\(textLabel!.text!)\(rowCount)"
        state[identifier] = sender.isChecked

    //Store state
    let checkedItems = state as Dictionary
    NSUserDefaults.standardUserDefaults().setObject(checkedItems, forKey: "packItems")
    NSUserDefaults.standardUserDefaults().synchronize()

}

func onLoadSet(){
    identifier = "\(textLabel!.text!)\(rowCount)"
    //Set state from stored State
    if var storedToDoItems: AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey("packItems") {

        if storedToDoItems != nil {
           var itemString = storedToDoItems as? Dictionary<String, Bool>
            if itemString![identifier] != nil {
                checkbox.isChecked = itemString![identifier] as Bool!
            }
        }
    }

}

OK I found it. 好,我找到了。 Unbelievable how simple it was in the end! 简直太简单了!

I just added an else satement to: 我只是添加了其他内容:

func onLoadSet(){
identifier = "\(textLabel!.text!)\(rowCount)"
//Set state from stored State
if var storedToDoItems: AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey("packItems") {

    if storedToDoItems != nil {
       var itemString = storedToDoItems as? Dictionary<String, Bool>
        if itemString![identifier] != nil {
            checkbox.isChecked = itemString![identifier] as Bool!
        }
    }
}

Working code: 工作代码:

func onLoadSet(){
    identifier = "\(textLabel!.text!)\(rowCount)"
    //Set state from stored State
    if var storedToDoItems: AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey("packItems") {

        if storedToDoItems != nil {
            println(storedToDoItems)
           var itemString = storedToDoItems as? Dictionary<String, Bool>
            if itemString![identifier] != nil {
                checkbox.isChecked = itemString![identifier] as Bool!
            } else {
                checkbox.isChecked = false
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM