Search code examples
iosswiftuiviewuibuttonxib

how to access custom view button action in main VC


I have created a custom view xib and give that view class. Now I take a view in main vc and give that class but now I want to access custom view button action method in my main vc. So how can I do that?

Here is my custom view

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) {
    }
}

image here

Now I create an outlet in my main VC and give that same class I can access those class outlets but now I want to access above button action method So how can I do that?


Solution

  • You can try

    let cusView = TextCustomisationVC(frame:///)
    

    if btn sender is used inside function

    cusView.btnCloseCustomisation_Click(cusView.closeBtn)
    

    otherwise send any dummy button

    cusView.btnCloseCustomisation_Click(UIButton())
    

    Edit:

    protocol CustomTeller {
        func closeClicked(UIButton)
    }
    
    class TextCustomisationVC: UIView {
    
        var delegate: CustomTeller?
    
        @IBAction func btnCloseCustomisation_Click(_ sender: UIButton) {
            self.delegate?.closeClicked(sender:sender)
        }
    }
    

    // in mainVC

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

    and implement

    func closeClicked(sender:UIButton) {
    
          // close button called 
    
    }