How to link another class of methods to UIButton

Asked 2 years ago, Updated 2 years ago, 36 views

When connecting methods to UIButton, you can write self as below, but how do you connect instance methods from other classes?
Also, please let me know if there is a website that I can refer to.

myButton.addTarget(self, action: "myFunction", forControlEvents:.TouchUpInside)

ios swift

2022-09-29 22:53

1 Answers

I don't do it often because it's troublesome to have other class instances with the information I need, but I just pass the other class instances instead of self, so I just need to do the following:

myButton.addTarget(theInstanceOfOtherClass, action: "myFunction", forControlEvents:.TouchUpInside)

UIControl Class Reference
Naturally, theInstanceOfOtherClass has generated an instance before calling this line, and the instance must remain for the duration of the action method being called.Normally, it would be the same ViewController instance property as having UIButton.

Then, the outline looks roughly like this.

class OtherClass {
    @objc func myFunction(){
        //...
    }
}

classViewController:UIViewController {

    @IBOutlet weak var myButton: UIButton!

    var theInstanceOfOtherClass=OtherClass()

    override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from anib.
        myButton.addTarget(theInstanceOfOtherClass, action: "myFunction", forControlEvents: .TouchUpInside)
        //...
    }

    //...
}

I'm not sure what I really want to do, but in some cases it might be better to consider other methods such as using the delete pattern.


2022-09-29 22:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.