Hey Guys Today We will See About how we can use the closure based call on the button. Previously we were used to use the addtarget and selector method as used in objective C .
Whenever we used to use addtarget instead of IBAction we needed to have the selector and the function to call the button Action
button.addTarget(self,action: #selector(buttonTapped),for: .touchUpInside)
Due to which we need we needed to Add objc func to perform the Action
Objc func buttonTapped() { count += 1 }
Now we no need to relay on selector instead of we can use the closure based Button call .
button.addAction(UIAction { [weak self ] _ in self?.counter += 1 }, for: .touchUpInside)
Bellow example is for the selector function as we use previously
Class ViewController: UIViewController { @IBOutlet weak var textLBL: UILabel! @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() button.addTarget(self,action: #selector(buttonTapped),for: .touchUpInside) } @objc func buttonTapped() { count += 1 self.textLBL.text = count.description ?? "" }
Now using the Closure in the button we can reduce the number of coding lines of the program
Class ViewController: UIViewController { @IBOutlet weak var textLBL: UILabel! @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() button.addAction(UIAction { [weak self ] _ in self?.count += 1 self?.textLBL.text = count.description ?? "" }, for: .touchUpInside) }