(Swift) Передача данных в другой viewController с помощью функции callBack - PullRequest
0 голосов
/ 14 февраля 2020

Ситуация:
У меня есть tableView со многими ячейками. Каждая ячейка имеет один и тот же тип / класс, а каждая ячейка имеет переключатель toggleSwitch.
Одна из ячеек или, точнее, ячейка в разделе 2, строка 0, когда переключатель переключается, необходимо обновить переменную типа bool в true / false (если переключатель включен => true). Эта переменная находится во втором V C.
. С кодом, приведенным ниже, не имеет значения, к какой ячейке подключены, она печатает switch is on/switch is off, но мне это нужно только для указанной выше ячейки.
Класс ячейки:

@IBOutlet weak var labelCell: UILabel!

@IBOutlet weak var cellSwitch: UISwitch!

@IBAction func toggleSwitch(_ sender: Any) {
    if cellSwitch.isOn == true {
        print("switch is on")
    }
    else {
        print("switch is off")
    }
}

В cellForRowAt:

case (2,0):
        cell.labelCell.text = "Shuffled"
        let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        let cardVC = (mainStoryboard.instantiateViewController(withIdentifier: "CardViewController") as! CardViewController)
        //place for condition, if switch is on/off, put the true/false to secondVC.shuffle
        cardVC.shuffle = true

Мой вопрос - как должна выглядеть моя функция обратного вызова, у меня нет с ними опыта. И как проверить, что эта (2,0) ячейка прослушивается?

1 Ответ

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

Объявите эту функцию callBack в файле tableViewCell, как показано ниже.

var callback:((Bool) -> Void)?

@IBAction func toggleSwitch(_ sender: Any) {
    if cellSwitch.isOn == true {
        print("switch is on")
        callback?(true)
    }
    else {
        print("switch is off")
        callback?(false)
    }
}


Вы можете получить нажатие строки, используя didSelectRowAt метод UITableViewDelegate .

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
if indexPath.section == 2 {
    if indexPath.row == 0 {
        // the tapped detect of (2,0)
    }
}
}

И вы можете получить действие UISwitch для вызова callBack с помощью метода cellForRowAt , как показано ниже.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   if indexPath.section == 2 {
      var cell = tableView.dequeueReusableCell(withIdentifier: "yourCell") as! YourCell
      if indexPath.row == 0 {
          //here you can write your callBack closure & your UISwitch's value will retrived here
          cell.callback = { [unowned self] check in
              cardVC.shuffle = check

          }
      }
   }
}
...