如何在单击一个按钮时发送事件

时间:2017-01-13 12:46:02

标签: ios iphone swift uibutton swift3

我创建了UIAlertView,它有2个按钮正按钮和负按钮。 AlertView也是viewcontroller。

我从Main viewController打开AlertVC。

这是我的AlertVC

class AlertVC: UIViewController {

    var transitioner : CAVTransitioner


    @IBOutlet weak var alertPositiveBtn: IFOButton!
    @IBOutlet weak var alertNegativeBtn: IFOButton!

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        self.transitioner = CAVTransitioner()
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        self.modalPresentationStyle = .custom
        self.transitioningDelegate = self.transitioner
    }

    convenience init() {
        self.init(nibName:nil, bundle:nil)
    }

    required init?(coder: NSCoder) {
        fatalError("NSCoding not supported")
    }



    @IBAction func postiveBtnPressed(_ sender: IFOButton) {

    }


    @IBAction func negativeBtnPressed(_ sender: IFOButton) {

    }


    @IBAction func closeBtnPressed(_ sender: UIButton) {
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }
}

我想要的是:我希望MainViewController以某种方式检测哪个按钮按下了负数或正数。

有人能告诉我怎么能这样做?

更新:使用委托模式后

@IBAction func positiveBtnPressed(_ sender: IFOButton) {
    delegate?.positiveBtnPressed(onAlertVC: self)
    self.presentingViewController?.dismiss(animated: true, completion: nil)
}

@IBAction func negativeBtnPressed(_ sender: IFOButton) {
    delegate?.negativeBtnPressed(onAlertVC: self)
    self.presentingViewController?.dismiss(animated: true, completion: nil)
}

以下是我在MainViewController上所做的事情

class MainViewController: UIViewController, AlertVCDelegate

这是我的功能

func positiveBtnPressed(onAlertVC: IFOAlertVC) {
    print("Pos")
    }
    func negativeBtnPressed(onAlertVC: IFOAlertVC) {
    print("Neg")}

它仍未被召唤。

2 个答案:

答案 0 :(得分:2)

这是delegate pattern

的教科书示例

向AlertVC添加协议:

protocol AlertVCDelegate : class {
    func positiveBtnPressed(onAlertVC: AlertVC)
    func negativeBtnPressed(onAlertVC: AlertVC)
}

然后在AlertVC类中创建一个weak属性并按下按钮:

class AlertVC : UIViewController {
    weak var delegate: AlertVCDelegate?
    ...
    @IBAction func postiveBtnPressed(_ sender: IFOButton) {
        delegate?.positiveBtnPressed(onAlertVC: self)
    }


    @IBAction func negativeBtnPressed(_ sender: IFOButton) {
        delegate?.negativeBtnPressed(onAlertVC: self)
    }
}

AlertVCDelegate中实施MainViewController协议,并在delegate提供AlertVC时设置MainViewController

如果您从segue中显示提醒vc,请使用prepare(for: sender:)方法将MainViewController设置为委托。

答案 1 :(得分:0)

您必须按CTRL +从应用故事板拖动按钮到他们自己的方法。

您的 IFOButton 应该是UIButton派生类(继承)。

即使你只需要一种方法来做到这一点

@IBAction internal func handleButtonTap(_ sendder: UIButton) -> Void
{
    if sender === alertPositiveBtn
    {
         // Do something positive here
    }
    else
    {
        // Do something negative here
    }
}
相关问题