我正在尝试使用this example
在TabBarController之间传递数据问题是,ViewController2中的标签不会更新。
以下是我使用的代码:
TabBarController:
import UIKit
class CustomTabBarController: UITabBarController {
var myInformation: [String ] = []
override func viewDidLoad() {
super.viewDidLoad()
}
ViewController1:
class ViewController1: UIViewController {
var items = [String]()
@IBOutlet weak var label: UILabel!
@IBAction func item1(_ sender: UIButton) {
items += ["Audi"]
print(items)
}
override func viewDidLoad() {
super.viewDidLoad()
if let tbc = self.tabBarController as? CustomTabBarController {
tbc.myInformation = items
}
}
ViewController2
class ViewController2: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if let tbc = self.tabBarController as? CustomTabBarController {
for item in tbc.myInformation {
label.text = item
}
}
}
我猜,因为
if let tbc = self.tabBarController as? CustomTabBarController {
tbc.myInformation = items
}
在viewDidLoad中,按下item1按钮时它不会更新? 但是X代码不允许我把它放在其他地方。 我应该如何获得更新阵列的按钮?
答案 0 :(得分:0)
我认为控制器1中存在问题:
if let tbc = self.tabBarController as? CustomTabBarController {
tbc.myInformation = items
}
因为您在ViewDidLoad中调用它,而ViewDidLoad仅在视图加载到内存时调用。在控制器1的数组中追加值时,需要更新值。
你必须更新myInformation数组:
@IBAction func item1(_ sender: UIButton) {
items += ["Audi"]
if let tbc = self.tabBarController as? CustomTabBarController {
tbc.myInformation = items //OR// tbc.myInformation.append("Audi")
}
print(items)
}