![](/img/trans.png)
[英]Add Item in UICollectionView From Another Another CollectionView (Swift)
[英]Swift UICollectionView - Add/remove data from another class
我先执行一个主视图控制器,如下所示,
MainViewController
class MainViewController: UIViewController {
var collectionView: UICollectionView!
var dataSource: DataSource!
SomeAction().call() {
self.dataSource.insert(message: result!, index: 0)
}
}
collectionview的DataSource
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
时, 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
。
Datasource类已使用其默认的nil值重新初始化,您必须将更新的类传递给下一个控制器以访问其更新状态。
如何添加/删除其他类中的数据?
这是最佳做法吗?
我可以将对话设为全局变量吗? 不,最好使用模型/ mvc样式。 模型上的数据,视图控制器上的ui。
似乎您的初始计数为1,但您在索引1(索引之外)处插入,请使用self.dataSource.insert(message: result!, index: 0)
代替
或使用append
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.