ios - 如何在Swift 3中使用addTarget方法

标签 ios swift selector

这是我的button对象

    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删除,则编译成功

最佳答案

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

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,因此工作代码变为:

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

关于ios - 如何在Swift 3中使用addTarget方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59900138/

相关文章:

iOS:如何在自定义单元格上正确使用 prepareForReuse?将编辑切换到非编辑模式时,我的单元格被错误地重复使用

ios - Xcode 7.1 : Failed to build project <Project Name> for scheme

java - setItemChecked 用于 ListView 的 Android 选择器在版本 2.2.1 中不起作用

nested - 我可以创建嵌套的 Angular 组件 HTML 选择器吗?

ios - 如何将 uitableview 中的单个单元格链接到不同的 URL?

ios - iOS 10 日志上的 TIC TCP 连接错误

ios - 如何从解析数组中删除项目?

css - 如何删除SCSS中的伪选择器?

ios - 将字节数组转换为 PDF 文件?

ios - 如何在 iOS 中使用 RTMP 为 Facebook、Youtube 等多个社交媒体创建直播