Ios Swift UICollectionView-从另一个类添加/删除数据
我首先执行了一个主视图控制器,如下所示 MainViewControllerIos Swift UICollectionView-从另一个类添加/删除数据,ios,swift,uicollectionview,uicollectionviewcell,Ios,Swift,Uicollectionview,Uicollectionviewcell,我首先执行了一个主视图控制器,如下所示 MainViewController class MainViewController: UIViewController { var collectionView: UICollectionView! var dataSource: DataSource! SomeAction().call() { self.dataSource.insert(message: result!, index: 0) } } open clas
class MainViewController: UIViewController {
var collectionView: UICollectionView!
var dataSource: DataSource!
SomeAction().call() {
self.dataSource.insert(message: result!, index: 0)
}
}
open class SomeController {
let dataSource: DataSource = DataSource()
public func createEvent() {
self.dataSource.insert(message: result!, index: 1)
}
}
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
class MainViewController: UIViewController {
var collectionView: UICollectionView!
var dataSource: DataSource!
SomeAction().call() {
self.dataSource.insert(message: result!, index: 0)
}
}
open class SomeController {
let dataSource: DataSource = DataSource()
public func createEvent() {
self.dataSource.insert(message: result!, index: 1)
}
}
当我从上面的控制器添加一些数据时,对话
是空的,没有现有的记录,并抛出错误:数组索引超出范围
。我可以理解这是因为我再次实例化了数据源
Datasource类已使用其默认的nil值重新初始化,您必须将更新的类传递给下一个控制器才能访问其更新的状态
- 您应该使用类Datasource:NSObject{
- 以及viewcontroller类上的集合视图委托
- 将数据源传递到PrepareForsgue中
- 对
Datasource类已使用其默认的nil值重新初始化,您必须将更新的类传递给下一个控制器才能访问其更新的状态
- 您应该使用类Datasource:NSObject{
- 以及viewcontroller类上的集合视图委托
- 将数据源传递到PrepareForsgue中
- 对
看起来您的初始计数是1,但您在索引1处插入(索引外) 使用
self.dataSource.insert(消息:result!,索引:0)
代替
或者使用
append
似乎您的初始计数是1,但您在索引1处插入(超出索引)
使用self.dataSource.insert(消息:result!,索引:0)
代替
或者使用
append
我没有使用序列图像板,我仍然可以使用prepareforsgue
或者有其他选择吗?我没有使用序列图像板,我仍然可以使用prepareforsgue
或者有其他选择吗?仍然错误:数组索引超出范围
?仍然错误:数组索引超出范围
?