ios - 将数据传递给 TabBar Controller

标签 ios iphone swift tabbar

我想在两个 ViewController 之间传递数据并抛出 TabBarController。 在第一个 ViewController 中,我找到了 textField 和按钮。 在第二个里面我找到了标签。 当我在 textField 中写入一些文本并按下按钮时,我希望该文本出现在第二个 ViewController 的标签中。但是没有任何反应。

还有我的代码:

第一个 View Controller :

import UIKit

class FirstViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    @IBAction func enter(_ sender: Any) {
        if textField.text != "" {
            if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController, let second = tabBarController.viewControllers?.first as? SecondViewController {
                second.label.text = textField.text
                tabBarController.selectedIndex = 0
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

第二个 View Controller :

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    var myString = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = myString
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

enter image description here

最佳答案

我觉得问题出在

tabBarController.viewControllers?.first as? SecondViewController

您可能想这样做:

tabBarController.viewControllers?[1] as? SecondViewController

不要忘记数组是从 0 开始索引的,所以 viewControllers?[1] 实际上返回数组中的第二个元素。

关于ios - 将数据传递给 TabBar Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47359065/

相关文章:

ios - Cocos2d : are there any possible run time errors if two sprites run the same CCAnimation from CCAnimationCache at the same time?

python - 使用 matplotlib 制作 3D 动画,连接点以创建移动简笔画

ios - 无法将类型 'UILabel!' 的值转换为预期参数 'type inout String'

ios - UIView center 属性给出了意想不到的结果

ios - CollectionView 在我的聊天 View 中按顺序更新和复制。 ( swift 4.2,Xcode)(MessengerKit)

iphone - 是否可以使用 "large"框架垂直对齐标签内的文本

ios - NSURLCache 不在 iOS 7 中存储缓存数据

iphone - 如何从 UIViewController 访问 UINavigationController

ios - wifi不存在时NEHotspotConfigurationManager报错问题

ios - 如何解决 Sqlite.swift 中的警告消息 'BUG IN CLIENT OF libsqlite3.dylib: database integrity compromised by API violation'?