如何在swift 3中使用addTarget方法 [英] how to use addTarget method in swift 3

查看:1936
本文介绍了如何在swift 3中使用addTarget方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的按钮对象

    let loginRegisterButton:UIButton = {
    let button = UIButton(type: .system)
    button.backgroundColor = UIColor(r: 50 , g: 80, b: 130)
    button.setTitle("Register", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitleColor(.white, for: .normal)
    button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside)
    return button
}()

这是我的函数

    func handleRegister(){

    FIRAuth.auth()?.createUser(withEmail: email, password: password,completion: { (user, error) in

        if error != nil
        { print("Error Occured")}

        else
        {print("Successfully Authenticated")}
    })        
}

我收到编译错误,如果addTarget删除它compi成功

I'm getting compile error, if addTarget removed it compiles successfully

推荐答案

是的,如果没有参数,请不要添加()

Yes, don't add "()" if there is no param

button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside). 

如果你想得到寄件人

button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside). 

func handleRegister(sender: UIButton){
   //...
}

编辑:

button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside)

不再有效,你需要更换 _ 在选择器中,您在函数头中使用了变量名,在这种情况下,它将是 sender ,因此工作代码变为:

no longer works, you need to replace _ in the selector with a variable name you used in the function header, in this case it would be sender, so the working code becomes:

button.addTarget(self, action:#selector(handleRegister(sender:)), for: .touchUpInside)

这篇关于如何在swift 3中使用addTarget方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆