如何在 main VC 中访问自定义视图按钮操作

how to access custom view button action in main VC

我创建了一个自定义视图 xib 并提供了该视图 class。现在我在 main vc 中查看并给出 class 但现在我想在我的 main vc 中访问自定义视图按钮操作方法。那我该怎么做呢?

这是我的自定义视图

import UIKit

class TextCustomisationVC: UIView {
    @IBOutlet var contentView: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.commonInit()
    }

    private func commonInit(){
        Bundle.main.loadNibNamed("TextCustomisationVC", owner: self, options: nil)
        addSubview(contentView)
        contentView.frame =  self.bounds
        contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }

    @IBAction func btnCloseCustomisation_Click(_ sender: Any) {
    }

    @IBAction func btnApplyCustomisation_Click(_ sender: Any) {
    }
}

现在我在我的主 VC 中创建了一个出口并提供了相同的 class 我可以访问那些 class 出口但现在我想访问上面的按钮操作方法 那么怎么才能我这样做?

你可以试试

let cusView = TextCustomisationVC(frame:///)

如果 btn sender 在函数内部使用

cusView.btnCloseCustomisation_Click(cusView.closeBtn)

否则发送任何虚拟按钮

cusView.btnCloseCustomisation_Click(UIButton())

编辑:

protocol CustomTeller {
    func closeClicked(UIButton)
}

class TextCustomisationVC: UIView {

    var delegate: CustomTeller?

    @IBAction func btnCloseCustomisation_Click(_ sender: UIButton) {
        self.delegate?.closeClicked(sender:sender)
    }
}

// 在 mainVC 中

let cusView = TextCustomisationVC(frame:///)
cusView.delegate = self

并实施

func closeClicked(sender:UIButton) {

      // close button called 

}

你可以在这里使用你可以在主程序中实现的委托VC。

创建这样的协议:

protocol ButtonActionDelegate {
   func closeButtonPressed(_ sender:UIButton)
   func applyButtonPressed(_ sender:UIButton)
}

然后像这样在您的视图中创建委托实例:

var delegate:ButtonActionDelegate?

像这样在 VC 中实现这个委托:

extension mainVC : ButtonActionDelegate {

    func closeButtonPressed(_ sender: UIButton) {
    }
    func applyButtonPressed(_ sender: UIButton) {
    }

}

然后可以这样分别调用delegate方法:

@IBAction func btnCloseCustomisation_Click(_ sender: Any) {
    self.delegate?.closeButtonPressed(sender)
}

@IBAction func btnApplyCustomisation_Click(_ sender: Any) {
    self.delegate?.applyButtonPressed(sender)
}