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
addTarget(_:action:for:) Associates a target object and action method with the control.
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!") }
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)
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(){ //... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With