IOS- swift : Passing data between ViewControllers inside UITabbarController

标签 ios swift uitabbarcontroller uitabbar

我正在做一个swift项目,UI设计已经给出如下图。

enter image description here

问题 我需要在个人资料 View Controller 和主页 View Controller 之间双向传递数据。

我已经尝试过: 内部主视图 Controller :

   override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(selectMypost), name: NSNotification.Name("com.rjt.Chao.postsCliked"), object: nil)
}
@objc func selectMypost(){
    isFiltering = true
    if let currentUserId = Auth.auth().currentUser?.uid {
        filteredPosts = posts.filter{
            $0.userID == currentUserId
        }
    }
    tblview.reloadData()
}

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    guard let curUserId = Auth.auth().currentUser?.uid else {return false}
    let count = posts.filter{$0.userID == curUserId}.count
    NotificationCenter.default.post(name: NSNotification.Name("com.rjt.Chao.mypostnumbercount"), object: self, userInfo: ["currentUserPostCount":count])
    print(viewController)
    return true
}

内部配置文件 View Controller :

    @objc func changeCounts(notification:Notification){
    guard let count = notification.userInfo!["currentUserPostCount"] else {return}
    posts.setTitle(String(count as! Int), for: .normal)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
            NotificationCenter.default.addObserver(self, selector: #selector(changeCounts), name: NSNotification.Name("com.rjt.Chao.mypostnumbercount"), object: nil)
}

但是当我第一次点击 Profile 标签项时,没有调用选择器函数,UIButton 标题没有改变。

我的猜测: 似乎应该在通知帖子之前添加观察员。我对吗?

如何解决这个问题?

最佳答案

创建一个全局结构/静态类,您可以在其中存储信息(选择最适合您的套件)。查看 MVC 和 Singleton 设计模式。基本上,MVC 是一种涉及将数据和 VC 完全分离的模式,以便您的 View 和 Controller 仅处理 UI 内容,并且只要它们需要访问信息,它们就会访问您的数据类。单例更像是我在顶部建议的。一个结构/类(通常是一个类),用于保存您的应用程序的数据。

关于IOS- swift : Passing data between ViewControllers inside UITabbarController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50635365/

相关文章:

ios - 我可以只使用 iPad 应用程序创建 watch 扩展吗?

ios - SwiftUI mask 圆角矩形内的矩形

iphone - 在OBJ-C中将完整字母转换为数字

ios - 由于 Transporter,我的应用程序不会上传。我怎样才能绕过这个?

ios - 错误 : index beyond bounds

ios - 在 drawRect 上动画创建 cgrect 不起作用

ios - 实例化 View Controller Swift 3 标签栏 Controller

ios - 单击按钮时加载 Tabbar Controller

iphone - UITabBarController - 初始框架和调整大小

ios - 迁移到 Xcode 10 后单元测试失败