TableView - Сохранение отдельной ячейки - PullRequest
0 голосов
/ 08 мая 2020
• 1000 при нажатии кнопки этой ячейки ячейка будет сохранена. Отдельная ячейка должна быть полностью доступна для просмотра в другом tableView. Я не понимаю, как я могу go делать это в коде, а также должен ли я использовать данные по умолчанию или основные данные пользователя, которые я видел во время исследования, что оба должны быть пригодны для использования.

RecipeTableViewController

import UIKit

class RecipeTableViewController: UITableViewController {



    @IBAction func downloadButtonTouched(_ sender: Any) {

    }

    //This is the search term that is imported by segue from SearchViewController.swift

    var searchTermImport: String = ""

    let recipe_API_Call = call_Edamam_API()

    var returned_Recipes = [Hit]()

    override func viewDidLoad() {
        super.viewDidLoad()
        print(searchTermImport)
        fetchRecipes()
    }
    //Calls the fetch function in Recipe_API_Caller.swift and attempts to return the results into the empty array "returned_Recipes" of type "Recipe".
    func fetchRecipes(){
        self.returned_Recipes = []
        self.tableView.reloadData()

        let query: [String: String] = [
            "q": searchTermImport,
            "app_id": "b1961989",
            "app_key": "e8caffc800ea5634edbc8b7c9616c61f"
        ]

        recipe_API_Call.fetch(matching: query, completion: {(returned_Recipes) in
            DispatchQueue.main.async {
                if let returned_Recipes = returned_Recipes{
                    self.returned_Recipes = returned_Recipes
                    self.tableView.reloadData()

                }
                else{
                    print("Fetch Error")
                }
            }
        })
    }

    //Configures the table with the results returned from the "fetchRecipes()" function.
    func configureTable(cell: UITableViewCell, forItemAt indexPath: IndexPath){
        let returned_Recipe = returned_Recipes[indexPath.row]

        cell.textLabel?.text = returned_Recipe.self.recipe.label

        cell.imageView?.image = #imageLiteral(resourceName: "unnamed")


        let network_task = URLSession.shared.dataTask(with: returned_Recipe.self.recipe.image){ (data, response, error)
            in
            guard let Image_dest = data else{
                return
            }
            DispatchQueue.main.async {
                let image = UIImage(data: Image_dest)
                cell.imageView?.image = image
            }
        }
        network_task.resume()
    }

    // MARK: - Table view data source


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return returned_Recipes.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath)

        // Configure the cell...
        configureTable(cell: cell, forItemAt: indexPath)
        return cell
    }


    override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.row)!")
    }

    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if let indexPath = tableView.indexPathForSelectedRow{
            guard let destinationVC = segue.destination as? RecipeDetailedViewController else{return}
            let selectedRow = indexPath.row
            destinationVC.RecipeName = returned_Recipes[selectedRow].recipe.label
            destinationVC.recipePicture = returned_Recipes[selectedRow].recipe.image
            destinationVC.seeMoreLink = returned_Recipes[selectedRow].recipe.url
            destinationVC.listOfIngredients = returned_Recipes[selectedRow].recipe.ingredientLines
        }
        }
    }

Это код, который заполняет tableView после того, как пользователь ищет термин, и я хочу, чтобы он сохранил эту ячейку в «Сохраненные рецепты. "TableView после нажатия кнопки загрузки.

The Search Results screen

Буду признателен за любой совет, который вы все можете дать! Спасибо!

1 Ответ

0 голосов
/ 09 мая 2020

Вы должны добавить свойство статуса в модель рецепта, изменить и сохранить его при нажатии, а затем в другом tableView получить рецепты, статус которых == загружен, и отобразить их.

enum RecipeStatus {
   case unDownload, downloaded, paid, finished
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   let recipe = recipes[indexPath.row]       
   recipe.status = downloaded
   YourDatabase.save(recipe)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...