我有第一執行的主視圖控制器,其看起來像下面,夫特UICollectionView - 添加/移除數據從另一個類
MainViewController
class MainViewController: UIViewController {
var collectionView: UICollectionView!
var dataSource: DataSource!
SomeAction().call() {
self.dataSource.insert(message: result!, index: 0)
}
}
數據源的的CollectionView的
class DataSource: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var conversation: [messageWrapper] = []
override init() {
super.init()
}
public func insert(message: messageWrapper, index: Int) {
self.conversation.insert(message, at: index)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return conversation.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let textViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "textViewCell", for: indexPath) as! TextCollectionViewCell
let description = conversation[indexPath.row].description
textViewCell.textView.text = description
return textViewCell
}
}
因此,當執行MainViewController
時,一個添加到collectionview的數據源中,它工作得很好。
問題 現在,我有另一個類,看起來像 SomeController
open class SomeController {
let dataSource: DataSource = DataSource()
public func createEvent() {
self.dataSource.insert(message: result!, index: 1)
}
}
當我從上面的控制器添加一些數據,該conversation
是空的不具有現有一個記錄並拋出Error: Array index out of range
。我可以理解,這是因爲我再次實例化了DataSource
。
- 如何添加/刪除其他類的數據?
- 這是最好的做法嗎?
- 我可以使對話成爲全局變量嗎?
我不使用故事板,我還可以使用'prepareForSegue'還是有其他選擇? – moustacheman