Вызовите тот же самый вид еще раз, чтобы в UITableViewController можно было выбрать другую опцию. - PullRequest
0 голосов
/ 23 февраля 2020

Справочная информация: Простое приложение, которое позволяет вам выбрать валюту из UITableViewController, снова вызывает то же представление, чтобы сделать второй выбор, затем переносит пользователя в новое представление, которое отображает две выбранные валюты и обменивает Оцените

Так что теоретически для меня это всего лишь 2 просмотра. Первая представляет собой список валют, а вторая представляет выбранные валюты / курсы обмена. Первый взгляд - полный дизайн. Но я борюсь за то, чтобы сделать связь между первым и вторым выбором, так как он вызывает одно и то же представление. Как бы я это сделал?

В моем didSelectRowAt я обычно выполняю сеанс, но как мне вызвать то же представление и записать значение, выбранное из первого представления? У меня была идея вызвать функцию, которая будет записывать, если выбрана опция, и если это так, вызывать новое представление, иначе снова вызвать то же самое представление, но я не уверен, как бы это реализовать. Любая помощь приветствуется!

Мой код пока:

import UIKit

class SelectCurrencyTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // Get the JSON data to insert into the table
    func parseJSONData()-> Array<Any> {
        var finalArray = [Any]()
        if let url = Bundle.main.url(forResource: "currencies", withExtension: "json") {
            do {
                let data = try Data(contentsOf: url)
                let jsonResult = try JSONSerialization.jsonObject(with: data)
                if var jsonArray = jsonResult as? [String] {

                    while jsonArray.count > 0 {
                        let result: [String] = Array(jsonArray.prefix(2))
                        finalArray.append(result)
                        jsonArray.removeFirst(2)
                    }
                }
            } catch {
                print(error)
            }
        }
        return finalArray
    }

    func checkOptionsCount()-> Int{
        // somehow check if option selected?
        return 1 
    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellController
        if let array = parseJSONData()[indexPath.row] as? [String]{
            cell.countryCodeLabel.text = array[0]
            cell.currencyLabel.text = array[1]
            cell.countryFlag.image = UIImage(named: array[0])
        }
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        // if this is 1st time, present view again
        if (checkOptionsCount() == 1){



        // if this is 2nd time, show new view
        } else if (checkOptionsCount() == 2){
             // performSegue with new view 


        } else {
            print("How did I get here")
        }
    }


    /*
    // 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.
    }
    */

}

1 Ответ

1 голос
/ 24 февраля 2020

Видя ваш код, я предполагаю, что вы используете раскадровки. Один из способов достижения sh того, что вы хотите, может быть следующим:

  1. В Интерфейсном Разработчике выберите ваш SelectCurrencyTableViewController и добавьте в него Storyboard ID: enter image description here
  2. Добавьте свойство, в котором вы будете хранить выбранную валюту, в SelectCurrencyTableViewController, примерно так:

    class SelectCurrencyTableViewController: UITableViewController {
    
        var selectedCurrency: Currency?
        //...
    }
    
  3. Тогда в didSelectRow:

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    
        // if this is 2nd time, show new view
        if let selected = selectedCurrency {
    
            // performSegue with new view 
    
        // if this is 1st time, present view again
        // these is no selected currency passed from previous view controller, so this is the first time
        } else {
    
            //get view controller from storyboard using storyboard id (replace "Main" with your storyboard's name
            let vc = UIStoryboard(name: "Main", bundle: nil)
                .instantiateViewController(withIdentifier: "SelectCurrencyTableViewController") as! SelectCurrencyTableViewController
            vc.selectedCurrency = //place code for getting first currency based on indexPath.row here
            show(vc, sender: self)
        }
    }
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...