无法转换类型" ViewController.Type"的值预期参数类型" UIViewController"

时间:2017-07-26 15:40:30

标签: ios swift

我试图制作一个警报控制器,如果答案是"确定",那么它将对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。'使捕获语义明确"

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:9)

所以要修复presentViewController(ViewController, animated: true, completion: nil)闭包中的okConfirmAction函数,试试这个:

self?.present(ViewController(), animated: true, completion: nil)

对于performSegue(withIdentifier:sender:)闭包中的okConfirmAction函数,请尝试:

self?.performSegue(withIdentifier: "teste", sender: self)

由于它是一个闭包,你必须在调用函数之前使用self。这是为了让您意识到可能会导致保留周期。

按如下方式编写闭包以防止保留周期(使用弱self引用意味着我们将self替换为self?作为present(_:animated:completion:)和{{1}的前缀}}):

performSegue(withIdentifier:sender:)

答案 1 :(得分:0)

使用performSegue(withIdentifier: "teste", sender: self)。我不确定您在(Any).之前使用self尝试实现的目标,因为类名称上的self会返回类型类的,不是类的实例。