简体   繁体   中英

Is there a different option than addTarget on a UIButton

addTarget

So I know that you can use addTarget on a button like so:

import UIKit

class ViewController: UIViewController {
    func calledMethod(_ sender: UIButton!) {
        print("Clicked")
    }

     override func viewDidLoad() {
        super.viewDidLoad()

        let btn = UIButton(frame: CGRect(x: 30, y: 30, width: 60, height: 30))
        btn.backgroundColor = UIColor.darkGray
        btn.addTarget(self, action: #selector(self.calledMethod(_:)), for: UIControlEvents.touchUpInside)
        self.view.addSubview(btn)
    }
}

This works absolutely fine but I was just wondering is there another way to detect when something is clicked and run some code when that happens.

You can add button in the storyboard and create an outlet for it's action.

@IBAction func buttonAction(_ sender: UIButton) {
  //implement your code here
}

You can also have a look at RxSwift/RxCocoa or similar. All the changes and actions are added automatically and you can decide if you want to observe them or not.

The code would look something like this:

   let btn = UIButton(frame: CGRect(x: 30, y: 30, width: 60, height: 30))
   btn.backgroundColor = UIColor.darkGray
   btn
      .rx
      .tap
      .subscribe(onNext: {
          print("Clicked")
      }).disposed(by: disposeBag)
   view.addSubview(btn)    

A button is a subclass of UIControl . A UIControl is designed to use target/action to specify code to run when the specified action occurs. If you don't want to use that mechanism, you have to create an equivalent.

You could attach a tap gesture recognizer to some other object and set it's userInteractionEnabled flag to true, but gesture recognizers ALSO use the target/action pattern.

My suggestion is to "stop worrying and learn to love the button." Just learn to use target/action.

Another possibility: Create a custom subclass of UIButton that sets itself up as it's own target at init time (specifically in init(coder:) and init(frame:) , the 2 init methods you need to implement for view objects.) This button would include an array of closures that its action method would execute if the button was tapped. It would have methods to add or remove closures. You'd then put such a button in your view controller and call the method to add the closure you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM