从警报处理程序返回超级功能

时间:2018-08-06 16:53:27

标签: swift uiviewcontroller

在我的shouldPerformSegue中,检查是否输入了所有玩家名称。如果没有,我问用户是否要继续。

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {

    // Check filled in players
    // var shouldPerform = true

    if (newPlayerCount < playerCount && newPlayerCount >= minPlayerCount) {
        let alert = UIAlertController(title: "Lege velden", message: "Je hebt een veld leeg gelaten. Weet je zeker dat je met \(newPlayerCount) spelers wilt spelen?", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ja", style: .default, handler: { action in
            //shouldPerform = true
            return true
        }))
        alert.addAction(UIAlertAction(title: "Nee", style: .destructive, handler: { action in
            self.markUnusedFields()
            //shouldPerform = false
            return false
        }))
        self.present(alert, animated: true)
    }
    //return shouldPerform
}

return无效,因为处理程序不期望它。如何从处理程序返回主函数?我也无法创建在处理程序中设置的变量(例如在注释中),因为该变量会立即返回。

谢谢!

2 个答案:

答案 0 :(得分:1)

shouldPerformSegue(withIdentifier:sender:)是弹出警报进行确认的正确位置。相反,您的控件应该连接到弹出确认的动作,然后然后您的动作可以调用performSegue(withIdentifier:sender:)

答案 1 :(得分:0)

在您的代码中,函数shouldPerformSegue发出警报,然后立即返回。 shouldPerformSegue完成后,便会执行警报操作。

我会尝试在用户按下继续按钮时显示警报,而不是尝试评估是否应该进行锁定。

@IBAction func touchedContinueButton(_ sender: UIButton) {
    // Check filled in players
    if (newPlayerCount < playerCount && newPlayerCount >= minPlayerCount) {
        let alert = UIAlertController(title: "Lege velden", message: "Je hebt een veld leeg gelaten. Weet je zeker dat je met \(newPlayerCount) spelers wilt spelen?", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ja", style: .default, handler: { action in
            // The player chose to continue
            // Send them to the next view using the segue with identifier "mySegue"
            self.performSegue(withIdentifier: "mySegue", sender: self)
        }))
        alert.addAction(UIAlertAction(title: "Nee", style: .destructive, handler: { action in
            self.markUnusedFields()
        }))
        self.present(alert, animated: true)
    }
}

如果您使用这种方法,请不要忘记设置segue的情节提要板标识符以匹配performSegue(withIdentifier:)

中的字符串