gpt4 book ai didi

ios - 使用自定义选项卡栏 Controller 类在两个 View Controller 之间传递数据

转载 作者:搜寻专家 更新时间:2023-10-31 08:21:27 25 4
gpt4 key购买 nike

我正在尝试使用选项卡栏 Controller 将数据从一个 View Controller 传递到另一个 View Controller 。我已经实现了一个自定义的 Tab Bar Controller 类。这是我为这门课编写的代码:

class CustomTabBarControllerClass: UITabBarController, UITabBarControllerDelegate {

override func awakeFromNib() {
self.delegate = self;
}

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
var logView = SecondViewController()
logView.log.append("Testing 123")
}

}

如您在我的代码中所见,我正在使用 logView 变量创建 SecondViewController 的实例。在我的 SecondViewController 类中,我有一个 log 数组设置,它将保存从我的 CustomTabBarControllerClass 类传递的值。这是我的 SecondViewController 代码。

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var log = [String]()

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return log!.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("logCell", forIndexPath: indexPath) as UITableViewCell

cell.textLabel.text = log![indexPath.row]

return cell
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
println(log!) //fatal error: unexpectedly found nil while unwrapping an Optional value
}

}

在我的 viewDidLoad() 函数中,我尝试使用 println(log!) 将日志打印到控制台。当此代码运行时,出现以下错误:fatal error: expectedly found nil while unwrapping an Optional value。那么我将如何在两个 View Controller 之间传递数据呢?

更新

didSelectViewController 函数已更新为以下代码,但是,我仍然收到相同的错误消息。

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
var logView = self.viewControllers![0] as SecondViewController
logView.log?.append("Testing 123")
}

最佳答案

您的标签栏 Controller 已经有一个 SecondViewController 的实例,所以您不应该实例化一个新的。使用选项卡栏 Controller 的 viewControllers 属性访问您想要的(大概是从名称,索引 1 处的那个)。

class ViewController: UIViewController {

var log = [String]()

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
println(log)
}
}

在标签栏 Controller 中,

class RDTabBarController: UITabBarController , UITabBarControllerDelegate{

override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
var logView = self.viewControllers![1] as ViewController
logView.log.append("Testing 123")
}

}

关于ios - 使用自定义选项卡栏 Controller 类在两个 View Controller 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27138271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com