代表:传递数据而不会引起争执 [英] Delegates: pass data without segue
问题描述
我有两个简单的类,可以像这样通过委托传递信息:
I have two simple classes that pass information with delegates like so:
protocol VCBDelegate: class {
func buttonDidPress() }
class ViewControllerBefore: UIViewController {
weak var delegate: VCBDelegate?
let vc = ViewController()
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = vc
}
@IBAction func press(_ sender: Any) {
delegate?.buttonDidPress()
} }
class ViewController: UIViewController, VCBDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
一切正常,并触发了buttonDidPress功能.但是我的问题是,如果我想重新加载集合视图,则由于我在ViewControllerBefore类中实例化ViewController对象的方式,该集合视图为nil.请记住,由于两个视图控制器未连接,因此我无法在segue中分配委托.
Everything works fine and the function buttonDidPress is triggered. But my problem is that if I want to reload a collection view, then the collection view is nil because of the way I instantiate the ViewController object in the ViewControllerBefore class. Keep in mind that I cannot assign the delegate in a segue, because the two view controllers are not connected.
请参见buttonDidPress函数下方的内容:
See here below the buttonDidPress function:
func buttonDidPress() {
dataCell.infoCell.insert(addDataCell.getBuyCell(), at: 0)
self.cvHome.reloadData()
}
推荐答案
在这种情况下,我喜欢将数据存储在 dataSource
内部.设置完毕后,我可以从应用程序中的任何位置访问数据.
I like to store the data inside of a dataSource
for these circumstances. I can access the data from anywhere in the app once it's been set.
class PageDataSource {
var theData : [Any]?
static let sharedInstance = PageDataSource()
private init() {}
}
为确保我将信息通过 delegate
传递并将其存储到 dataSource
中,我执行以下操作:
To make sure I pass the info through the delegate
and I store it to the dataSource
I do this:
func doDelegate() {
PageDataSource.sharedInstance.theData = whatever
passData(whatever)
dismiss(true, nil)
}
然后,我确保 tableView
或 collectionView
正在从 PageDataSource.sharedInstance.theData
获取所需的信息,例如:>
Then I make sure that the tableView
or collectionView
is getting the information it needs from PageDataSource.sharedInstance.theData
for example:
// MARK: CollectionView DataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if PageDataSource.sharedInstance.theData.count >= 1 {
return PageDataSource.sharedInstance.theData.count
}
return 0
}
这篇关于代表:传递数据而不会引起争执的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!