问题
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.
Any help would be appreciated!
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:
回答1:
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.
To save an array of favorites:
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()
}
来源:https://stackoverflow.com/questions/37513754/add-cell-to-favorites-tableview-with-core-data