【问题标题】:How to hide container view from another view controller Swift如何从另一个视图控制器 Swift 中隐藏容器视图
【发布时间】:2020-12-20 06:53:13
【问题描述】:

这是 Main.storyboard 的截图。

我正在尝试根据视图控制器隐藏-取消隐藏 audioBarView(StartingViewController 的容器视图)。在屏幕截图中,我展示了该视图在哪些地方需要,哪些地方不需要。

我尝试在 BrowserVC 或其他任何地方创建 StartingViewController 的实例,但它触发了错误(audioBarView = nil)。

如果您需要更多信息,请回复。

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您可以使用NotificationCenter 从您想要的视图控制器中触发一个事件,该事件可以包含附加信息,即显示/隐藏容器视图。

    在您的StartingViewController 中,您可以定义一个负责显示/隐藏容器视图的函数。在viewDidLoad 中,您可以添加如下观察者:

    NotificationCenter.default.addObserver(self, selector: #selector(playerVisibilityNeedsChangeNotification(notif:)), name: Notification.Name(rawValue: "PlayerVisibilityNeedsToBeUpdate"), object: nil)
    

    StartingViewController 中定义事件处理函数

    func changePlayerVisibility(show: Bool) {
        self.playerContainerView.isHidden = !show
    }
    
    @objc func playerVisibilityNeedsChangeNotification(notif: Notification) {
        let show = notif.object as? Bool ?? false
        self.changePlayerVisibility(show: show)
    } 
    

    从您想要的视图控制器发布通知:

    let show = false
    NotificationCenter.default.post(name: Notification.Name(rawValue: "PlayerVisibilityNeedsToBeUpdate"), object: show)
    

    【讨论】:

    • 我还建议在不再显示视图时调用removeObserver,以防止内存泄漏。
    【解决方案2】:

    虽然 NotificationCenter 非常适合解耦,但有时您也可以考虑使用回调进行父子通信。例如。 “Now Playing Music”是“Starting View Controller”的子级。

    你可以使用:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get child view controller(s) using segue.destination and keep a reference to it.
        // provide callback handler for some event
    
        // in the callback handler, you can directly invoke any function in a relevant child ViewController via reference.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-27
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多