将@IBAction链接到ViewController的.xib视图中的按钮

问题描述 投票:0回答:3

我已经为我的iOS应用程序中的重复创建了一个.xib文件,其中有一个UIButton。

我在故事板中的多个UIViewControllers中包含了.xib视图。我想将@IBAction和@IBOutlet链接到我的.xib视图中的按钮,该视图特定于每个UIViewController。换句话说,我希望每个UIViewController都能完全管理和处理.xib视图中的UIButton。

知道上述是否可行?

ios swift xcode uiviewcontroller xib
3个回答
0
投票

有几种方法可以做你想要的。

我这样做的方法是给你的自定义视图一个在触发IBAction方法时运行的闭包。并且从xib加载视图的每个视图控制器都可以将闭包传递给视图,并且当单击按钮时操作将运行。


0
投票

所以这是我迄今为止提出的最佳解决方案。

  1. 在我的.xib中,我将按钮链接到一个空的@IBAction。
  2. 再次在我的.xib中,我创建了一个带有单个方法的协议,我将在步骤(1)中创建的@IBAction中调用该方法。
  3. @IBAction将在每次调用时运行协议方法,因此每次单击该按钮时都是如此。
  4. 在每个需要处理@IBAction的ViewController中实现协议存根,并确保使用步骤(2)中创建的协议将该ViewController链接到.xib

0
投票

在包含xib视图的ViewController中,只需将操作分配给xib视图中的按钮

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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.