在 Swift / iOS 中从 UITableView 删除行并从 NSUserDefaults 更新数组的正确方法

2023-12-09

从中删除行的正确方法是什么UITableView并从 NSUserDefaults 更新数组?

在下面的示例中,我正在读取一个数组NSUserDefaults并喂养一个UITableView及其内容,我还允许用户删除UITableView我不确定什么时候读取和写入NSUserDefaults因此,一旦删除一行,表就会更新。正如你所看到的,我首先读取数组中的viewDidLoad方法并将其重新保存在commitEditingStyle方法。使用这种方法,删除行时我的表不会重新加载。

override func viewDidLoad() {
    super.viewDidLoad()
     // Lets assume that an array already exists in NSUserdefaults.
     // Reading and filling array with content from NSUserDefaults.
    let userDefaults = NSUserDefaults.standardUserDefaults()
    var array:Array = userDefaults.objectForKey("myArrayKey") as? [String] ?? [String]()
}

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

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel!.text = array[indexPath.row]
    return cell
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        array.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }
  // Save array to update NSUserDefaults     
 let userDefaults = NSUserDefaults.standardUserDefaults()
 userDefaults.setObject(array, forKey: "myArrayKey")


 // Should I read from NSUserDefaults here right after saving and then reloadData()?
 }

通常如何处理这种情况?

Thanks


基本上它是正确的,但只有在删除了某些内容时才应该保存在用户默认值中。

if editingStyle == .delete {
    array.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: .automatic)
    let userDefaults = UserDefaults.standard
    userDefaults.set(array, forKey: "myArrayKey")
}
  

不需要也不推荐读回数组。

In cellForRowAtIndexPath重用单元格时,需要在 Interface Builder 中指定标识符。

let cell = tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) 

数据源数组必须在类的顶层声明

var array = [String]()

然后将值赋给viewDidLoad并重新加载表视图。

override func viewDidLoad() {
    super.viewDidLoad()

    let userDefaults = UserDefaults.standard
    guard let data = userDefaults.array(forKey: "myArrayKey") as? [String] else {
        return 
    }
    array = data
    tableView.reloadData()
}   
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Swift / iOS 中从 UITableView 删除行并从 NSUserDefaults 更新数组的正确方法 的相关文章

随机推荐