【问题标题】:how to access custom view button action in main VC如何在主 VC 中访问自定义视图按钮操作
【发布时间】:2018-09-19 00:20:47
【问题描述】:

我创建了一个自定义视图 xib 并提供该视图类。现在我在主 vc 中查看并给出该类,但现在我想在我的主 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 中创建了一个 outlet,并提供了同一个类,我可以访问这些类 outlet,但现在我想访问上面的按钮操作方法那么我该怎么做呢?

【问题讨论】:

  • 您是否尝试过直接在主 VC 中实现这些操作?然后您可以使用addTarget(_,action:,for:) 将目标操作添加到主VC 中的按钮。
  • 我可以这样做,但我必须为此采取措施并创建该按钮的自定义操作,我想将在 xib 中创建的相同操作访问到主 vc
  • 您的问题不清楚。您想在主 VC 中获取操作,但您也尝试从自定义视图访问操作方法。这令人困惑。

标签: ios swift uiview uibutton xib


【解决方案1】:

您可以在此处使用委托,您可以在主 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) {
    }

}

然后你可以像这样分别调用委托方法:

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

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

【讨论】:

  • 错过了一步,即当我们在 mainVC 中初始化 UIView 时需要设置委托。 customeView.delegate = self 否则不起作用。
【解决方案2】:

你可以试试

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 中获得了 cusView.btnCloseCustomisation_Click,但我必须将什么作为参数传递?
  • 好的,当我在 Xib 中单击该按钮时,我怎样才能进入我的主 vc?根据您的回答,我无需点击即可提前完成此操作
  • 你需要使用委托
  • 你能发布详细的答案吗?你想说我必须为此创建协议?
猜你喜欢
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
相关资源
最近更新 更多