Reason: 'attempt to insert item 0 into section 1, but there are only 1 sections after the update'
原因:'尝试将第0项插入第1部分,但更新后只有1个部分'
I don't understand what the problem is. If the array is being inserted into section 1 and there is (only) 1 section then why can it not be inserted?
我不明白问题是什么。如果将数组插入到第1部分并且(仅)1部分,那么为什么不能插入?
var ref: FIRDatabaseReference!
var messages: [FIRDataSnapshot]! = []
private var refHandle: FIRDatabaseHandle!
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
collectionView?.registerClass(ChatLogCollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView?.backgroundColor = UIColor.blueColor()
}
override func viewWillAppear(animated: Bool) {
self.messages.removeAll()
collectionView?.reloadData()
refHandle = self.ref.child("messages").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in
self.messages.append(snapshot)
print(self.messages.count) //temp
self.collectionView?.insertItemsAtIndexPaths([NSIndexPath(forRow: self.messages.count - 1, inSection: 1)])
})
}
Cell Code:
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.messages.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ChatLogCollectionCell
}
1 个解决方案
#1
1
You are inserting something into section 1
, which means there must be 2
sections because numbering starts at 0
. When iOS checks the consistency of your data by calling numberOfSectionsInCollectionView
which returns 1
, it notes the inconsistency.
您正在向第1部分插入内容,这意味着必须有2个部分,因为编号从0开始。当iOS通过调用返回1的numberOfSectionsInCollectionView来检查数据的一致性时,它会注意到不一致。
Change the section number you are inserting into to 0
.
将要插入的部分编号更改为0。
self.collectionView?.insertItemsAtIndexPaths([NSIndexPath(forItem: self.messages.count - 1, inSection: 0)])
#1
1
You are inserting something into section 1
, which means there must be 2
sections because numbering starts at 0
. When iOS checks the consistency of your data by calling numberOfSectionsInCollectionView
which returns 1
, it notes the inconsistency.
您正在向第1部分插入内容,这意味着必须有2个部分,因为编号从0开始。当iOS通过调用返回1的numberOfSectionsInCollectionView来检查数据的一致性时,它会注意到不一致。
Change the section number you are inserting into to 0
.
将要插入的部分编号更改为0。
self.collectionView?.insertItemsAtIndexPaths([NSIndexPath(forItem: self.messages.count - 1, inSection: 0)])