在另一个ViewController中快速访问ContainerView中的UIButton

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

我在从另一个UIButton访问ContainerView内的ViewController时遇到问题。

如果用户点击button,则SubView应该出现在我的ViewController内部。我尝试将button文件中的ViewController拖动到创建@IBAaction func tapped(),但这无法正常工作。

仅在ContainerView.swift文件内部起作用。但是我无法在此处创建我的Subview ...

希望您能解决我的问题,感谢您的帮助!

enter image description here

ios swift uiviewcontroller uicontainerview
2个回答
0
投票

您可以使用NotificationCenter来实现。

在您的ContainerViewController中,您可以在单击按钮时发布通知

@IBAction func yourBtnTap(sender : UIButton) { 
NotificationCenter.default.post(name: Notification.Name("myBtnTapped"), object: nil)
} 

在CurrentViewController中,您必须先注册才能接收此通知。因此,在您的viewDidLoad中,执行以下操作:

NotificationCenter.default.addObserver(self, selector: #selector(self.myBtnTappedAction(notification:)), name: Notification.Name("myBtnTapped"), object: nil)

现在在CurrentViewContoller中创建myBtnTappedAction函数,只要轻按按钮即可调用该函数。

@objc func myBtnTappedAction(notification : Notification) { 
// now you can perform all your actions here. this function will be called everytime the button in the container view is tapped.
}

0
投票

您可以使用ViewController属性将其ContainerView移到parent内部。因此,在您的ContainerView类中:

self.parent?.showSubView() // your method to show the sub view.
© www.soinside.com 2019 - 2024. All rights reserved.