使用核心数据将单元格添加到收藏夹 tableview [英] Add cell to favorites tableview with core data
问题描述
我有一个 iOS 应用,我想让人们在 tableview 单元格上滑动以将该单元格添加到收藏夹页面 tableview.
I have an iOS app that I would like to have people swipe on a tableview cell to add that cell to the favorites page tableview.
它必须使用核心数据,以便在应用退出后保存收藏夹.
It would have to use core data so that the favorites save after app exit.
任何帮助将不胜感激!
这是我到目前为止的单元格滑动操作:
This is what I have so far for the cell swipe action:
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let favorite = UITableViewRowAction(style: .Normal, title: "Favorite") { (action, indexPath) in
// share item at indexPath
self.editing = false
print("Favorited \(indexPath.row)")
}
favorite.backgroundColor = UIColor.greenColor()
return [favorite]
}
这是我的收藏夹页面代码.
This is my code for the favorites page.
var favorites : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
favorites = vars.favs
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return favorites.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = favorites[indexPath.row]
cell.textLabel!.text = object
return cell
}
这是如何添加收藏夹的图片:
This is a picture of how the favorites will be added:
推荐答案
如果您需要将收藏夹列表作为字符串保存在您的应用程序中,您或许可以简单地使用 NSUserDefaults 而不是核心数据.
If a list of favourites as Strings is all you need to persist in your app, you might be able to simply use NSUserDefaults instead of Core Data.
要保存一系列收藏夹:
let favorite = UITableViewRowAction(style: .Normal, title: "Favorite") { (action, indexPath) in
var favorites : [String] = []
let defaults = NSUserDefaults.standardUserDefaults()
if let favoritesDefaults : AnyObject? = defaults.objectForKey("favorites") {
favorites = favoritesDefaults! as [String]
}
favorites.append(tableView.cellForRowAtIndexPath(indexPath).textLabel!.text)
defaults.setObject(favorites, forKey: "favorites")
defaults.synchronize()
}
要阅读收藏夹页面中的收藏夹数组:
To read the array of favorites in your favorites page:
var favorites : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
if let favoritesDefaults : AnyObject? = defaults.objectForKey("favorites") {
favorites = favoritesDefaults! as [String]
}
self.tableView.reloadData()
}
这篇关于使用核心数据将单元格添加到收藏夹 tableview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!