Использовать переход для элемента, выбранного в виде таблицы - PullRequest
0 голосов
/ 07 мая 2020

Я рассмотрел другие возможные решения здесь, в StackOverflow, но не совсем думаю, что они применимы к моей проблеме, или просто, я не понимаю, большая вероятность. Вот что я пытаюсь сделать. У меня есть табличное представление с разделами и элементами в каждом разделе. Я хочу перейти к другому контроллеру представления на основе выбора, сделанного пользователем в табличном представлении. Я создал образец со следующим кодом с сегментами «report1Segue» и «report2Segue» в качестве примера.


class ViewController: UIViewController {

    @IBOutlet weak var reportTableView: UITableView!

    let reportGroup = ["Dietary", "Weight", "Sleep", "Meditation", "Fitness"]

    let report = [["Calorie Breakdown", "Net Calories"], ["Last 3 Months"], ["Last 3 Months"],["Last 3 Months"],["Exercises by Type"]]

    func numberOfSections(in tableView: UITableView) -> Int {
        return report.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return reportGroup[section]
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "reportSegue" {
            if let reportVC = segue.destination as? Report1ViewController, let indexPath = reportTableView.indexPathForSelectedRow {

                reportVC.dataToDisplay = report[indexPath.section][indexPath.row]
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return report[section].count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = report[indexPath.section][indexPath.row]

        return cell

    }
}

extension ViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "report1Segue", sender: nil)
    }

}

Любое руководство всегда приветствуется.

Ответы [ 2 ]

1 голос
/ 07 мая 2020

Swift 5.2

Для фиксированных данных в UITableView вы можете сделать это так:

// Hard code your IndexPath references
// This will make the code easier to read in the delegate methods
enum TableIndex {
    static let calorieBreakdown =          IndexPath(row: 0, section: 0)
    static let netCalories =               IndexPath(row: 1, section: 0)
    static let weightLastThreeMonths =     IndexPath(row: 0, section: 1)
    static let sleepLastThreeMonths =      IndexPath(row: 0, section: 2)
    static let meditationLastThreeMonths = IndexPath(row: 0, section: 3)
    static let fitnessExercises =          IndexPath(row: 0, section: 4)
}


// Example - perform whatever Segues you actually need
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath {
    case TableIndex.calorieBreakdown:
        performSegue(withIdentifier: "report1Segue", sender: self)
    case TableIndex.weightLastThreeMonths, TableIndex.sleepLastThreeMonths:
        performSegue(withIdentifier: "report2Segue", sender: self)
    default:
        break
    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let indexPath = tableView.indexPathForSelectedRow else { return }
    let data = report[indexPath.section][indexPath.row]

    switch segue.identifier {
    case "report1Segue":
        if let dest = segue.destination as? Report1ViewControler {
            dest.dataToDisplay = data
        }
    case "report2Segue":
        if let dest = segue.destination as? Report2ViewControler {
            dest.dataToDisplay = data
        }
    default:
        break
    }
}
0 голосов
/ 07 мая 2020

Похоже, что здесь должно произойти 1, в вашем didSelectRowAt вам нужно выяснить, что было задействовано, поэтому в зависимости от того, как вы отображаете ячейки, вам нужно сделать то же самое здесь, чтобы узнать, что ячейка прослушивается. Затем на основе этого выбора у вас будет либо случай переключения, либо операторы if else, каждый из которых будет вызывать свой уникальный performSegue, так что на основе выбора ячейки он будет go для другого выбора.

Для вашего Например, ваш «выбор» - это report [indexPath.section] [indexPath.row]

тогда, если переключатель или иначе, если будет как

if selection == "Last 3 Months" || selection == "Net Calories" {
    performSegue(withIdentifier: "report1Segue", sender: nil)
} else if selection == "Calorie Breakdown" {
    performSegue(withIdentifier: "report2Segue", sender: nil)
}

Надеюсь, это поможет вам.

...