gpt4 book ai didi

ios - 向左滑动 uitableViewCell 时将 tableView Item 保存为默认值

转载 作者:行者123 更新时间:2023-11-28 10:27:22 24 4
gpt4 key购买 nike

我关注了This向左滑动并单击最喜欢的按钮时,回答将我的数据保存在数组中。我到目前为止所做的就是这个

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { (action, indexPath) in
var favorites : [String] = []
let defaults = UserDefaults.standard
if let favoritesDefaults : AnyObject? = defaults.object(forKey: "favorites") as AnyObject {
favorites = favoritesDefaults! as! [String]
}

let cell = self.myTableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! TableViewCell
favorites.append(itemList[indexPath.row])
defaults.set(favorites, forKey: "favorites")
defaults.synchronize()
}
return [favorite]
}

数组列表

   var itemList = [ "item1", "item2", "item3", "item4", "item5", 
"item6", "item7", "item8", "item" , "item", "Gobbling"]

当我点击最喜欢的按钮时出现错误

Could not cast value of type 'NSNull' (0x22e386f28) to 'NSArray' (0x22e386960)

最佳答案

不要将 cellForRowAt 之外的单元格出列。永远不要那样做。无论如何,该单元都未被使用。

使用专用 API array(forKeyUserDefaults 读取数组并将类型转换为预期类型而不是未指定的 Any(Object)

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { [unowned self] (action, indexPath) in
let defaults = UserDefaults.standard
var favorites = defaults.array(forKey: "favorites") as? [String] ?? []
favorites.append(self.itemList[indexPath.row])
defaults.set(favorites, forKey: "favorites")
}
return [favorite]
}

关于ios - 向左滑动 uitableViewCell 时将 tableView Item 保存为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58245979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com