what is the difference between addAction and addTarget

Viewed 700

I was thinking about button click events and we have different options

  • UITapGestureRecognizer
  • addTarget
  • addAction

for a basic operation let's say

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

@objc private func buttonClicked () {
    print("button clicked")
}

however we can do the same thing without going through objc functions or selectors using the following

extension UIControl {
    func addAction(for controlEvents: UIControl.Event = .touchUpInside, _ closure: @escaping()->()) {
        addAction(UIAction { (action: UIAction) in closure() }, for: controlEvents)
    }
}

button.addAction(for: .touchUpInside) { [weak self] in
      guard let self = self else {return}
      self.buttonClicked()
}

func settingsClicked () {
    print("settings clicked")
}

I took a look at apple's documentation for addAction and could not find much there and I was wondering the difference between the two and which one should I use more

1 Answers

The addTarget(_:action:for:) approach uses target/action, the old Objective-C based dynamic dispatch approach where you provide a target object and a selector.

If you are targeting iOS ≥14, you can use the newer addAction(_:for:) which allows you to provide a UIAction object, which includes a closure. It's more modern, but won't work for iOS <14.

Related