我有一个包含两个 View Controller 的标签栏 Controller 。我想将数据从第一个 View Controller 传递到第二个 View Controller 。我目前正在使用单例方法:
class Items {
static let shared = Items()
var array = [Item]()
}
第一个 View Controller 负责填充共享数组。
class FirstiewController: UIViewController {
func appendElement() {
let newItem = Item()
Items.shared.array.append(newItem)
}
}
每次 View 显示在屏幕上时,第二个 View Controller 应该检索数组。
class SecondViewController: UIViewController {
internal var items: [Item] = []
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
items = Items.shared.array
}
}
这并不理想,出于性能原因,我想仅在将新值添加到数组时才获取。我们如何添加监听器,以便仅在应用向数组追加新元素时才获取数据?
最佳答案
使用委托(delegate)模式
首先为您的 Items
类创建协议(protocol)
protocol ItemsDelegate {
func newItemAdded()
}
然后在 Items
类中为您的委托(delegate)创建变量,并在您的 array
设置新值时调用委托(delegate)方法
class Items {
var delegate: ItemsDelegate?
static let shared = Items()
var array = [Item]() {
didSet {
delegate?.newItemAdded()
}
}
}
然后在 viewDidLoad
中将单例的委托(delegate)设置为 self
override func viewDidLoad() {
...
Items.shared.delegate = self
}
然后将此协议(protocol)实现到您的 ViewController 并声明添加新项目时应该发生什么
class SecondViewController: UIViewController, ItemsDelegate {
...
func newItemAdded() {
items = Items.shared.array
}
...
}
关于ios - 在选项卡 Controller 中的两个 View Controller 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53719985/