Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use addTarget method in swift 3

here is my button object

    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 }() 

and here is my function

    func handleRegister(){      FIRAuth.auth()?.createUser(withEmail: email, password: password,completion: { (user, error) in          if error != nil         { print("Error Occured")}          else         {print("Successfully Authenticated")}     })         } 

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

like image 925
Ninja13 Avatar asked Sep 21 '16 13:09

Ninja13


People also ask

What is addTarget Swift?

addTarget(_:action:for:) Associates a target object and action method with the control.

How do I create a button action in Swift?

SwiftUI's button is similar to UIButton , except it's more flexible in terms of what content it shows and it uses a closure for its action rather than the old target/action system. To create a button with a string title you would start with code like this: Button("Button title") { print("Button tapped!") }


2 Answers

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

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

and if you want to get the sender

button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside).   func handleRegister(sender: UIButton){    //... } 

Edit:

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

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) 
like image 193
Damien Romito Avatar answered Sep 21 '22 04:09

Damien Romito


Try this with Swift 4

buttonSection.addTarget(self, action: #selector(actionWithParam(_:)), for: .touchUpInside) @objc func actionWithParam(sender: UIButton){     //... }  buttonSection.addTarget(self, action: #selector(actionWithoutParam), for: .touchUpInside) @objc func actionWithoutParam(){     //... } 
like image 35
Soumen Avatar answered Sep 24 '22 04:09

Soumen