Множественный выбор в режиме редактирования и передача данных в другое место

У меня есть Tabview с двумя вкладками (Мои истории и Избранное). Когда я вхожу в режим редактирования в Моих историях, я хочу иметь возможность выбирать несколько историй для добавления в Избранное. Код у меня есть, работает в определенной степени. Я могу выбрать несколько историй, но когда я нажимаю кнопку «Добавить в избранное», в «Избранное» добавляется только последняя выбранная история. Я не могу понять, как сохранить все выбранные истории в Избранное. Вот соответствующий код:

   func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        row = indexPath.row
        if tableView.cellForRowAtIndexPath(indexPath)?.selected == true {

        addToFavorites(row)

        }
    }
    func addToFavorites(row: Int) {
        passedTitle = storyTableViewTitle[row]
        passedText = storyTableViewText[row]
        doneEditingRows()
    }


    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, addNewStoryViewControllerDelegate, editStoryTextDelegate, UITabBarControllerDelegate {
    @IBOutlet var tableView: UITableView!

    var storyTableViewTitle = [String]()
    var storyTableViewText = [String]()
    var row = Int()
     func addNewStory() {
        performSegueWithIdentifier("showNewStory", sender: self)
    }

    func addToFavorites() {
        passedTitle.append(storyTableViewTitle[row])
        passedText.append(storyTableViewText[row])
        doneEditingRows()
    }

    func editRows() {
        tableView.allowsMultipleSelectionDuringEditing = true
        if storyTableViewTitle != [] {
        tableView.editing = true
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "doneEditingRows")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add Favorite", style: .Plain, target: self, action: "addToFavorites")
        } else {
            navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "editRows")
            navigationItem.leftBarButtonItem?.enabled = false
        }

    }
    func doneEditingRows() {

        tableView.editing = false
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "editRows")
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addNewStory")
        if storyTableViewTitle == [] {
            navigationItem.leftBarButtonItem?.enabled = false
        }
    }

    func tableView(tableView: UITableView, didEndEditingRowAtIndexPath indexPath: NSIndexPath) {
        tableView.editing = false
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "editRows")
        navigationItem.rightBarButtonItem?.enabled = true
        if storyTableViewTitle == [] {
            navigationItem.leftBarButtonItem?.enabled = false
        }
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return storyTableViewTitle.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

        cell.textLabel?.text = storyTableViewTitle[indexPath.row]
        cell.accessoryType = .DetailButton

        return cell
    }
    func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {

        let val = storyTableViewTitle.removeAtIndex(sourceIndexPath.row)
        let val1 = storyTableViewText.removeAtIndex(sourceIndexPath.row)

        storyTableViewTitle.insert(val, atIndex: destinationIndexPath.row)
        storyTableViewText.insert(val1, atIndex: destinationIndexPath.row)

    }
    func tableView(tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: NSIndexPath) {
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "doneEditingRows")
        navigationItem.rightBarButtonItem?.enabled = false
    }

    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

        let deleteAction = UITableViewRowAction(style: .Destructive, title: "Delete") {(action, indexPath) in

            self.storyTableViewTitle.removeAtIndex(indexPath.row)
            self.storyTableViewText.removeAtIndex(indexPath.row)

            let defaults = NSUserDefaults.standardUserDefaults()

            defaults.setObject(self.storyTableViewText, forKey: "storyText")
            defaults.setObject(self.storyTableViewTitle, forKey:"storyTitle")
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

            tableView.reloadData()

        }
        let favoriteAction = UITableViewRowAction(style: .Default, title: "Favorite") {(action, indexPath) in
            passedTitle.append(self.storyTableViewTitle[indexPath.row])
            passedText.append(self.storyTableViewText[indexPath.row])
            tableView.reloadData()
        }
        favoriteAction.backgroundColor = UIColor.greenColor()
        return [deleteAction,favoriteAction]
    }
    func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
        row = indexPath.row
        performSegueWithIdentifier("showStory", sender: self)
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if tableView.cellForRowAtIndexPath(indexPath)?.selected == true {
            row = indexPath.row
        }
    }
    import UIKit

var passedTitle = [String]()
var passedText = [String]()

class FavoritesTableViewController: UITableViewController, editStoryTextDelegate {


    var favoriteTitles = [String]()
    var favoriteTexts = [String]()
    var row = Int()



   override func viewDidLoad() {
        super.viewDidLoad()



    let defaults = NSUserDefaults.standardUserDefaults()
    if let storyTextArray = defaults.objectForKey("favoriteStoryText") as? [String] {
        favoriteTexts = storyTextArray
    }
    if let storyTitleArray = defaults.objectForKey("favoriteStoryTitle") as? [String] {
        favoriteTitles = storyTitleArray
    }

    tableView.reloadData()



        navigationController?.navigationBar.barStyle = .Black
        navigationController?.navigationBar.tintColor = UIColor.redColor()
    navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.redColor()]

    navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "editRows")

    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)


        // use for defaults reset

//        favoriteTitles = []
//        favoriteTexts = []
//        let defaults = NSUserDefaults.standardUserDefaults()
//        defaults.setObject(favoriteTitles, forKey: "favoriteStoryTitle")
//        defaults.setObject(favoriteTexts, forKey: "favoriteStoryText")

        if passedTitle != [] {
            if passedText != [] {
                favoriteTitles.append(passedTitle[row])
                favoriteTexts.append(passedText[row])
                passedTitle = []
                passedText = []

                let defaults = NSUserDefaults.standardUserDefaults()

                defaults.setObject(self.favoriteTexts, forKey: "favoriteStoryText")
                defaults.setObject(self.favoriteTitles, forKey:"favoriteStoryTitle")
                tableView.reloadData()
            }
        }
        if favoriteTitles != [] {
            navigationItem.leftBarButtonItem?.enabled = true
        } else {
            navigationItem.leftBarButtonItem?.enabled = false
        }

    }
       //MARK: TabelView Delegates

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("favoritesCell", forIndexPath: indexPath)
        cell.textLabel?.text = favoriteTitles[indexPath.row]
        return cell
    }
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        row = indexPath.row
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        performSegueWithIdentifier("showFavoriteStory", sender: self)
    }
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            favoriteTitles.removeAtIndex(indexPath.row)
            favoriteTexts.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)


            let defaults = NSUserDefaults.standardUserDefaults()

            defaults.setObject(self.favoriteTexts, forKey: "favoriteStoryText")
            defaults.setObject(self.favoriteTitles, forKey:"favoriteStoryTitle")


            tableView.reloadData()

        }
    }
    override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
        let val = favoriteTitles.removeAtIndex(sourceIndexPath.row)
        let val1 = favoriteTexts.removeAtIndex(sourceIndexPath.row)

        favoriteTitles.insert(val, atIndex: destinationIndexPath.row)
        favoriteTexts.insert(val1, atIndex: destinationIndexPath.row)
    }
    override func tableView(tableView: UITableView, didEndEditingRowAtIndexPath indexPath: NSIndexPath) {
        tableView.editing = false
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "editRows")
        navigationItem.rightBarButtonItem?.enabled = true
        if favoriteTitles == [] {
            navigationItem.leftBarButtonItem?.enabled = false
        }
    }
   override func tableView(tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: NSIndexPath) {
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "doneEditingRows")

    }

person Dusan Juranovic    schedule 05.01.2016    source источник


Ответы (1)


func addToFavorites(row: Int) {
passedTitle = storyTableViewTitle[row]
passedText = storyTableViewText[row]
doneEditingRows()
}

Глядя на приведенный выше код, кажется, что passedTitle и passedText - это обычные строковые переменные, и, следовательно, они сохраняют только последнюю выбранную строку, поскольку могут содержать только одно значение. Чтобы выбрать несколько значений, вы можете изменить эту переменную на Array

вы можете объявить Array в Swift следующим образом:

var passedTitle = [String]() //Empty array of type String
var passedText = [String]()

Ниже функция будет изменена на:

func addToFavorites(row: Int) {
    passedTitle.append(storyTableViewTitle[row])
    passedText.append(storyTableViewText[row])
    doneEditingRows()
    }

Следовательно, ваш вышеуказанный массив будет сохранять значения каждый раз, когда вы выбираете строку. вы можете использовать цикл for для извлечения данных из массива.

Надеюсь это поможет. :)

person Ajeet Pratap Maurya    schedule 05.01.2016
comment
Причина, по которой они были объявлены как простые строки, заключается в том, что они объявлены в другом месте вне класса, поэтому я могу получить к ним доступ из других классов, и затем после установки они будут добавлены к другому массиву. Однако я изменил их по вашему предложению, но это не помогло. Я все еще плохо разбираюсь в циклах и не знаю, как их правильно реализовать, и я думаю, что это может быть ответом. Я разместил еще немного кода, чтобы вы лучше поняли, каковы мои намерения. - person Dusan Juranovic; 05.01.2016
comment
Хорошо, я сделал это, хотя и без циклов. Спасибо, что указали мне правильное направление. За это вы заслужили мой голос :) - person Dusan Juranovic; 05.01.2016