Объединить сделал SelectRowAt с prepareForSegue? - PullRequest
0 голосов
/ 06 июня 2018

Я хотел бы разграничить то, что отправляется через prepareForSegue.

Например;если верхняя ячейка в tableView (indexPath.row == 0), я хотел бы отправить через firstVariable, и если indexPath.row == 1, я хотел бы отправить через secondVariable, и так далее.

Я попробовал это без удачи:

   let starterInfoSegueIdentifier = "ToStarterInfoSegue"

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        if indexPath.row == 0
        {
             func prepare(for segue: UIStoryboardSegue, sender: Any?)
            {
                if segue.identifier == starterInfoSegueIdentifier
                {
                    let destination = segue.destination as! Starter2ViewController
                    let starterIndex = tableView.indexPathForSelectedRow?.row
                    destination.name = startersArray[starterIndex!]
                    destination.variable = firstVariable
                }

            }
        }
    }    

РЕДАКТИРОВАТЬ:
Вот обновленный код:

class StartersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    let startersArray = ["ArrayItem1", "ArrayItem2"]


    var firstVariable = 1
    var secondVariable = 10

    @IBOutlet weak var tableView: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self

    }

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

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "StartersCell") as! StartersTableViewCell

        //Set round corners
        cell.cellView.layer.cornerRadius = cell.layer.frame.height / 2

        cell.startersLabel.text = startersArray[indexPath.row]

        return cell
    }



        let starterInfoSegueIdentifier = "ToStarterInfoSegue"

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        self.performSegue(withIdentifier:starterInfoSegueIdentifier,sender:indexPath.row)
    }


    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == starterInfoSegueIdentifier
        {
            let destination = segue.destination as! Starter2ViewController
            let index = sender as! Int
            destination.name = startersArray[index]
            destination.counter =  index == 0 ? firstVariable : secondVariable

        }

    }

}    

Код для tableViewCell:

import UIKit

class StartersTableViewCell: UITableViewCell {

    @IBOutlet weak var cellView: UIView!
    @IBOutlet weak var startersLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
}

Ответы [ 2 ]

0 голосов
/ 07 июня 2018

Я вижу в вопросе, а также ответ, что indexPath или indexPath.row передается как любой параметр функции executeSegue (withIdentifier).

Я полагаю, что простой подход заключается в определении переменной класса, скажемstartersArrayIndexToPass, чтобы сохранить индекс элемента, который будет передан.Сохраните эту переменную в методе tableview (didSelectRowAt) и используйте ее в функции prepare (segue :).При таком подходе избегается преобразование известного типа в Any и последующее приведение к типу Any для знания типа.

0 голосов
/ 06 июня 2018

Подготовка должна быть областью действия класса

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    self.performSegue(withIdentifier:starterInfoSegueIdentifier,sender:indexPath.row)
}

//

func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
        if segue.identifier == starterInfoSegueIdentifier
        {
             let destination = segue.destination as! Starter2ViewController
             let index = sender as! Int 
              destination.name = startersArray[index]
              destination.variable =  index == 0 ? firstVariable : secondVariable

         }

}

Если у вас много переменных, тогда я предлагаю создать struct для содержания вашей модели, а затем добавить ее объектывнутри startersArray и доступ из свойств объекта структуры

struct MyContent {
    var name:String
    var otherVar:String
}

, затем рефакторинг к этому

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    self.performSegue(withIdentifier:starterInfoSegueIdentifier,sender:startersArray[indexPath.row])
}

//

func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
        if segue.identifier == starterInfoSegueIdentifier
        {
             let destination = segue.destination as! Starter2ViewController
             let item = sender as! MyContent
              destination.name = item.name
              destination.variable = item.otherVar

         }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...