无法将“ViewController.Type”类型的值转换为预期的参数类型“UIViewController”
我正在尝试制作一个警报控制器,如果答案是“Ok”,那么它将对MapView执行一个segue。 这是完整的代码:
@IBAction func teste(_ sender: Any) { // Create the alert controller let alertController = UIAlertController(title: "Reservar vaga?", message: "Uma vaga será reservada em Estapar Estacionamento.", preferredStyle: .alert) // Create the actions let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {(alert:UIAlertAction) -> Void in let confirmAction = UIAlertController(title: "Vaga confirmada", message: "Gostaria de ter direções ao local?", preferredStyle: .alert) let okConfirmAction = UIAlertAction(title:"Sim", style: UIAlertActionStyle.default, handler:{(alert:UIAlertAction) -> Void in presentViewController(ViewController, animated: true, completion: nil) }) let noConfirmAction = UIAlertAction(title:"Não", style: UIAlertActionStyle.default) { UIAlertAction in NSLog("Ok Pressed") } confirmAction.addAction(okConfirmAction) confirmAction.addAction(noConfirmAction) self.present(confirmAction, animated: true, completion: nil) }) let cancelAction = UIAlertAction(title: "Cancelar", style: UIAlertActionStyle.cancel) { UIAlertAction in NSLog("Cancel Pressed") } // Add the actions alertController.addAction(okAction) alertController.addAction(cancelAction) //Append the button to the view self.present(alertController, animated: true, completion: nil) }
我在这部分遇到了麻烦:
let okConfirmAction = UIAlertAction(title:"Sim", style: UIAlertActionStyle.default, handler:{(alert:UIAlertAction) -> Void in presentViewController(ViewController, animated: true, completion: nil) })
当我尝试使用presentViewController时,会出现此错误:“无法将类型”ViewController.Type“的值转换为预期的参数类型’UIViewController’”
当我尝试使用performSegue时,我会这样使用:
performSegue(withIdentifier: "teste", sender: (Any).self)
然后出现以下错误:“Implitcit在关闭时使用self;使用’self。’ 使捕获语义显式“
谁能帮帮我吗?
所以要在okConfirmAction
闭包中修复presentViewController(ViewController, animated: true, completion: nil)
函数,试试这个:
self?.present(ViewController(), animated: true, completion: nil)
对于okConfirmAction
闭包中的performSegue(withIdentifier:sender:)
函数,请尝试:
self?.performSegue(withIdentifier: "teste", sender: self)
由于它是一个闭包,你必须在调用函数之前使用self。 这是为了让您意识到可能会导致保留周期。
编写闭包如下以防止保留周期(使用弱self
引用意味着我们将self
替换为self?
作为present(_:animated:completion:)
的前缀present(_:animated:completion:)
和performSegue(withIdentifier:sender:)
):
let okConfirmAction = UIAlertAction(title:"Sim", style: UIAlertActionStyle.default, handler:{ [weak self] (alert:UIAlertAction) -> Void in //insert code from above })
使用performSegue(withIdentifier: "teste", sender: self)
。 我不确定你想用(Any).
实现什么(Any).
在self
之前,因为类名上的self
返回类的类型 ,而不是类的实例。