简体   繁体   中英

UIButton not performing action from function in a different class

I have a class where written is a function creating my button:

LoginButton.swift

func createButton() {
    let myButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(Foo().buttonPressed(_:)), for: .touchUpInside)

    }()
}

Now in my second class, Foo.swift, I have a function that just prints a statement

Foo.swift

@objc func buttonPressed(_ sender: UIButton) {
    print("button was pressed")
}

When ran I get no errors except when I try to press the button, nothing happens. Nothing prints, the UIButton doesn't react in any way. Really not sure where the error occurs because Xcode isn't printing out any type of error or warning message.

The action method is called in the target object. Thus, you have either to move buttonPressed to the class which contains createButton or to pass an instance of Foo as a target object.

But note that a button is not the owner of its targets. So, if you just write:

button.addTarget(Foo(), action: #selector(buttonPressed(_:)), for: .touchUpInside)

This will not work, because the Foo object is immediately released after that line. You must have a strong reference (eg a property) to Foo() like

let foo = Foo()

func createButton() {
    let myButton: UIButton = {
        let button = UIButton()
        button.addTarget(foo, action: #selector(buttonPressed(_:)), for: .touchUpInside)

    }()
}

You are missing with target. So make instant of target globally and make use of it as target for button action handler.

class ViewController: UIViewController {

let foo = Foo()

override func viewDidLoad() {
    super.viewDidLoad()
    createButton()
}

func createButton() {
    let myButton: UIButton = {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
        button.backgroundColor = UIColor.red
        button.setTitle("Tap me", for: .normal)
        button.addTarget(self.foo, action: #selector(self.foo.buttonPressed(_:)), for: .touchUpInside)
        return button
    }()
    myButton.center = self.view.center
    self.view.addSubview(myButton)
}
}

Class Foo:

class Foo {

    @objc func buttonPressed(_ sender: UIButton) {
        print("button was pressed")
    }
}

Just pass Selector as function argument.

func createButtonWith(selector: Selector) {


    let myButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: selector), for: .touchUpInside)

    }()

}

And call this function like below...

createButtonWith(selector: #selector(Foo().buttonPressed(_:)))

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