Swift: Creating a button that calls a method in another class1

霸气de小男生 提交于 2019-12-03 08:56:35

Assuming that you have a view controller where you create the Store object - you should pass the button action back to this view controller and add a segue from it to your desired destination.

Best practice is to use a protocol that delegates the buttons action back up to the viewController that it is contained in as below.

Store.swift

protocol StoreDelegate {
    func didPressButton(button:UIButton)
}

class Store: UIView {

    var delegate:StoreDelegate!

    override init(frame:CGRect) {
        super.init(frame:frame)

        var button = UIButton()
        button.setTitle("button", forState: .Normal)
        button.addTarget(self, action: "buttonPress:", forControlEvents: .TouchUpInside)
        self.addSubview(button)
    }

    func buttonPress(button:UIButton) {
        delegate.didPressButton(button)
    }

}

ViewController.swift

class ViewController: UIViewController, StoreDelegate {

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

    func addStoreObj() {
        var store = Store()
        store.delegate = self // IMPORTANT
        self.view.addSubview(store)
    }

    func didPressButton(button:UIButton) {
        self.performSegueWithIdentifier("ok", sender: nil)
    }

}

This code is untested, but I hope you get the idea - your Store object delegates the button press activity back to its containing ViewController and then the ViewController carries out the segue that you have attached to it in the Storyboard.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!