【问题标题】:Swift - access UIButton inside ContainerView in another ViewControllerSwift - 在另一个 ViewController 中访问 ContainerView 内的 UIButton
【发布时间】:2019-11-21 18:13:02
【问题描述】:

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

如果用户点击buttonSubView 应该出现在我的ViewController 内。我尝试在ViewController 文件中拖动button 以创建@IBAaction func tapped(),但这不起作用。

它只适用于ContainerView.swift 文件。但我不能在那里创建我的Subview...

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

import UIKit

class ContainerViewController: UIViewController {




    override func viewDidLoad() {
        super.viewDidLoad()


        // Do any additional setup after loading the view.
    }


    @IBAction func addButtonTapped(_ sender: Any) {
        print("add Button")         
}

【问题讨论】:

  • 您可以添加屏幕截图吗?这会有所帮助!
  • 请放心。
  • 更新了答案。

标签: ios swift uiviewcontroller uicontainerview


【解决方案1】:

您可以使用 NotificationCenter 和 Delegates 来实现此目的。这是使用 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.
}

【讨论】:

  • 感谢您的回答 :) 但@Muhamed Gül 的回答对我来说看起来更简单
  • 由于我无法得到其他工作的答案,我尝试过并且效果很好:) 谢谢!
  • 很高兴为您提供帮助 :)
【解决方案2】:

您可以在ContainerView 中使用parent 属性访问您的ViewController。所以,在你的 ContainerView 类中:

if let parentVC = self.parent as? ViewController {
     parentVC.showSubView() // your method to show the sub view.
}

【讨论】:

  • 它对我不起作用。我无法从我的ViewController 在我的ContainerVIew 中访问任何func
  • @DieGlueckswurst 我已经更新了答案,请重新检查。
  • 对你有用吗?因为我遇到了 6 个错误:D
  • 另一个答案实际上对我有用,即使那不是很顺利
  • @DieGlueckswurst 是的,它工作得很好。你得到什么错误?我希望您不要尝试使用名为 showSubView() 的方法,这只是一个示例。而且我还假设您的父视图控制器的类是ViewController,因为它在您的问题中看起来像这样。如果没有,请将 as? ViewController 更改为 as? YourParentClassName 或任何名称。
猜你喜欢
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 2016-12-28
  • 2016-03-15
  • 2018-12-24
  • 2017-10-01
相关资源
最近更新 更多