Search code examples
iosuibuttonaddtarget

Fixing "use of unresolved identifier 'addTarget'" while adding func to button click event


I've created a UIButton programmatically as shown below:

let buttons: [UIButton] = [UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))];

Now if I try to add a function to it programmatically like this:

[buttons[0] addTarget:self action:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside]

I get an error saying that addTarget is not defined. How do I fix this?


Solution

  • you are try to use the Objective-C syntax in swift, this is entirely wrong, use your code as like

     buttons.first?.addTarget(self, action: #selector(self.buttonClicked(_:)), for: .touchUpInside)
    

    and handle the action as like

     @objc func buttonClicked( _ sender: UIButton) {
           print("buttonClicked Action Found")
    
    }
    

    Ref : Apple Document for UIButton