Sonya Kovach
Sonya Kovach

Reputation: 49

addTarget to custom button Swift 4

I have a problem with addTarget to my custom button in Swift 4. I tried everything, but still have problem to define selector, because result is always error.

Any idea?

let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
myButton.center = CGPoint(x: 200, y: 400)
myButton.backgroundColor = UIColor.purple
myButton.layer.cornerRadius = 18.0
myButton.setTitle("Tap Me", for: UIControlState.normal)
myButton.setTitleColor(UIColor.white, for: UIControlState.normal)
myButton.actions(forTarget: self, forControlEvent: UIControlEvents.touchUpInside)
myButton.isHighlighted = true
self.view.addSubview(myButton)

Upvotes: 0

Views: 4310

Answers (1)

iParesh
iParesh

Reputation: 2368

Try this

myButton.addTarget(self, action: #selector(self.btnClickAction(_:)), for: .touchUpInside)

Button action method

@objc func btnClickAction(_ sender:UIButton) {
        print("My custom button action")
    }

Upvotes: 3

Related Questions