При выполнении DidSelectRowAt переменные больше не имеют своих значений - PullRequest
0 голосов
/ 31 марта 2020

Я сейчас работаю над одним проектом, но столкнулся с этой проблемой. При выполнении didSelectRowAt переменные, которые не присваиваются при инициализации, удаляются. По сути, мне нужно получить значение того, какую строку я выбрал ранее, если сделал. Я сделал этот проект, чтобы упростить проблему. У меня есть два ViewController, и когда я щелкаю по любой из строк в tableView на первом ViewController, он переключается на второй ViewController. Там значение меняется в исходном проекте. Когда возвращаюсь к первому ViewController, мне нужно сравнить это indexValue со строкой, по которой я щелкаю. Любой совет будет оценен. :)

Первый ViewController

var globalIndex: Int!
var delegate: passDataDelegate!
let valueForExample = "This is just to show, how program behaves."

func passData(index: Int?) {
    globalIndex = index
    //When printing globalIndex, it shows normal value
}

let array = ["Row 1", "Row 2", "Row 3", "Row 4"]

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "customTableView", for: indexPath) as! CustomTableViewCell
    cell.label.text = array[indexPath.row]
    return cell
}

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

    print("Global index is \(globalIndex)")
    //When printing globalIndex, the value is always nil, however when I print valueForExample it normally shows its value
    if(globalIndex == indexPath.row) {
        print("You pressed the same button as before")
    }
    let secondVC = storyboard?.instantiateViewController(withIdentifier: "secondVC") as! SecondViewController
    delegate = secondVC
    delegate.passData(index: indexPath.row)
    secondVC.modalPresentationStyle = .fullScreen
    present(secondVC, animated: true)
}

@IBOutlet weak var tableView: UITableView!

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

}

func initialConfiguration() {
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "customTableView")
}

Второй ViewController

protocol delegate {
    func passData(index: Int?)
}
class SecondViewController: UIViewController, passDataDelegate {

    var globalIndex: Int!
    var delegat: delegate!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func button(_ sender: UIButton) {
        let firstVC = storyboard?.instantiateViewController(withIdentifier: "firstVC") as! ViewController
        delegat = firstVC
        delegat.passData(index: globalIndex)
        dismiss(animated: true, completion: nil)
    }

    func passData(index: Int) {
        globalIndex = index
    }
}

1 Ответ

0 голосов
/ 31 марта 2020

Во втором контроллере представления

var globalIndex: Int? //Make global index optional

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

    print("Global index is \(globalIndex)")

    if(globalIndex == indexPath.row) {
        print("You pressed the same button as before")
    }

    let secondVC = storyboard?.instantiateViewController(withIdentifier: "secondVC") as! SecondViewController
    secondVC.delegat = self // Set delegate
    secondVC.globalIndex = indexPath.row //Set global index
    secondVC.modalPresentationStyle = .fullScreen
    present(secondVC, animated: true)
}

extension FirstViewController: passDelegate {
    func passData(index: Int?){
        globalIndex = index // Set index from second view controller to first viewcontroller
    }
}

Во втором контроллере просмотра

protocol passDelegate {
    func passData(index: Int?)
}

class SecondViewController: UIViewController {
   var globalIndex: Int!
   var delegat: delegate!

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

   @IBAction func button(_ sender: UIButton) {
       delegat.passData(index: globalIndex) //Call delegate
       dismiss(animated: true, completion: nil)
   }
 }
...