Add cell to favorites tableview with core data

对着背影说爱祢 提交于 2019-12-05 10:45:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!