情况:
我有很多单元格的tableView。每个单元格都有相同的类型/类,每个单元格都有一个toggleSwitch。
切换开关时,其中一个单元格,或更确切地说是第2节第0行的单元格,需要将bool类型的变量更新为true / false(如果switch开启=> true)。该变量位于第二个VC中。
在下面的代码中,点击哪个单元格无关紧要,它会打印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)单元是否被窃听?
答案 0 :(得分:1)
将以下所示的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)
}
}
您可以使用 UITableViewDelegate 的 didSelectRowAt 方法获得行点击。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 2 {
if indexPath.row == 0 {
// the tapped detect of (2,0)
}
}
}
您可以从 cellForRowAt 方法(如显示波纹管)中获得UISwitch的回叫点击动作。
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
}
}
}
}