ios - 如何检测容器嵌入 UINavigationController 推送何时显示新 View

标签 ios swift xcode

我在 Storyboard中创建了 UIViewController (A),并使用 UINavController 添加了容器。

我嵌入的 UINavController 的根是带有按钮的 UIViewController (B)。

如果我点击按钮,NavController 会显示新的 UIViewController (C)。

所以我有 UINavController -> B -> C。A Controller 如何检测其包含的 NavController 内的 B -> C 转换?

最佳答案

有多种方法可以做到这一点,但最简单的解决方案可能是使用通知中心。每当通知发布时,您都会监听通知,为其指定一个唯一的名称,例如 ViewA 或 ViewB 通知,然后监听具有该名称的通知。检查下面的示例:-

import UIKit

struct NotificationNames {
    static let bViewController
    static let cViewController
}



class AViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Listen for notification of from BViewcontroller
        NotificationCenter.default.addObserver(self, selector: #selector(didLoadBViewController), name: Notification.Name(NotificationNames.bViewController), object: nil)

        // Listen for notification of from CViewcontroller
           NotificationCenter.default.addObserver(self, selector: #selector(didLoadCViewController), name: Notification.Name(NotificationNames.cViewController), object: nil)

    }


    @objc private func didLoadBViewController() {
        print("B ViewController is loaded.")
    }

    @objc private func didLoadCViewController() {
           print("C ViewController is loaded.")
       }

    // Remove notification listeners to save some memory
    deinit {
        NotificationCenter.default.removeObserver(self, name: NotificationNames.bViewController, object: nil)
         NotificationCenter.default.removeObserver(self, name: NotificationNames.cViewController, object: nil)
    }

}


class BViewcontroller: UIViewController {

    // Post notification that B ViewController loaded.
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        NotificationCenter.default.post(name: NotificationNames.bViewController, object: nil)
    }

}

class CViewController: UIViewController {

     // Post notification that C ViewController loaded.
    override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(true)
        NotificationCenter.default.post(name: NotificationNames.cViewController, object: nil)
     }

}

关于ios - 如何检测容器嵌入 UINavigationController 推送何时显示新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59466883/

相关文章:

ios - Swift——在 App Delegate 中实例化一个没有 Storyboard的导航 Controller

Xcode崩溃日志: "NO_CRASH_STACK + 0"

ios - 从 Obj-C 中的其他类访问实例方法

objective-c - 将 NSMutableString 分配给 UILabel 文本

ios - subview 中的 @State 和 @Published 属性,SwiftUI

ios - 枚举 NSString 的最佳方法

ios - 我的主要场景中所有 IBOutlets 都是零

ios - 如何垂直实现自动调整大小的 UITextView?

ios - 无法访问当前登录 Facebook 用户的相册 - Swift

ios - 如何将子类 View Controller 的 View 放入父类(super class)基 View Controller 的内容 View 中?