简体   繁体   中英

Link an @IBAction to a button in a .xib view from a ViewController

I have created a .xib file for a view that is going to be repetitive in my iOS app, inside of which there is a UIButton.

I have included that .xib view inside multiple UIViewControllers in my storyboard. I would like to link an @IBAction and an @IBOutlet to the button inside my .xib view that is specific to each UIViewController. In other words, I want every UIViewController to completely manage and handle the UIButton that is inside the .xib view.

Any idea if the above is feasible?

There are a couple of ways to do what you want.

The way I would do it is to give your custom view a closure that is run when the IBAction method is triggered. And each view controller that loads the view from the xib can pass in the closure to the view and the action will run when the button is clicked.

So here's the best solution I came up with so far.

  1. Inside my .xib, I link the button to an @IBAction that is empty.
  2. Again inside my .xib, I created a protocol with a single method that I will call inside the @IBAction created in step (1.)
  3. The @IBAction will run the protocol method every time it is called, so every time the button is clicked.
  4. Implement the protocol stub in every ViewController that needs to handle the @IBAction, and make sure to link that ViewController to the .xib using the protocol created in step (2.)

In your ViewController witch contains the xib view, just asign an action to the button inside xib view

class YourViewController:UIViewController{
    override func viewDidLoad(){
        //ListTitleView : a xib view, action button witch called theManageButton is inside it.
        let theListTitleView = ListTitleView.init(frame:CGRect.init(x: 0, y: 0, width:  self.view.frame.width, height: 100))

        //Add action to theManageButton
        theListTitleView.theManageButton.addTarget(self, action: #selector(yourFunction(Sender:)), for: .touchUpInside)
    }

    func yourFunction(Sender:UIButton){
        //...Do something here
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM