我在UITableViewCell from this tutorial裏學到了UICollectionView。uitableviewcell裏面的uicollectionview滾動會因索引超出範圍
它完美,只有當所有的集合視圖具有相同的numberOfItemsInSection
,所以它可以滾動,不會造成指數超出範圍錯誤,但是如果collection視圖細胞numberOfItemsInSection
是不同的,當我滾動集合視圖它由於索引超出範圍而崩潰。
我發現原因,當我滾動tableview,集合視圖單元格索引路徑更新根據底部,但我滾動的集合視圖是頂部一個,所以它不記得numberOfItemsInSection
,所以它會崩潰由於索引超出範圍。
PS:這是滾動的,但只有當底部是表格單元格,因爲它是numberOfItemsInSection
對應於細胞,不會造成Index out of range
。
這是我的CollectionView的numberOfItemsInSection
,我實際上有兩個集合的看法,但我認爲這是沒有問題的
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numberOfItemsInSection: Int = 0
if collectionView == self.collectionview_categorymenu {
let categories = self.json_menucategory["menu_categories"].arrayValue
numberOfItemsInSection = categories.count
} else {
let menuitems = self.json_menucategory["menu_items"].arrayValue
let item_data = menuitems[self.itemimages_index].dictionaryValue
let menu_item_images = item_data["menu_item_images"]?.arrayValue
numberOfItemsInSection = (menu_item_images?.count)!
print(numberOfItemsInSection)
}
return numberOfItemsInSection
}
這是我的CollectionView的cellForItemAt indexPath
:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.collectionview_categorymenu {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryMenuCell", for: indexPath) as! CategoryMenuCell
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemImagesCell", for: indexPath) as! ItemImagesCell
let menuitems = self.json_menucategory["menu_items"].arrayValue
let item_data = menuitems[self.itemimages_index].dictionaryValue
let menu_item_images = item_data["menu_item_images"]?.arrayValue
print(menu_item_images!)
let itemimage_data = menu_item_images?[indexPath.item].dictionaryValue
print("===\(indexPath.item)===")
let itemimage_path = itemimage_data?["image"]?.stringValue
let itemimage_detail = itemimage_data?["detail"]?.stringValue
if let itemimage = cell.imageview_itemimage {
let image_url = itemimage_path?.decodeUrl()
URLSession.shared.dataTask(with: NSURL(string: image_url!) as! URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print("error")
return
}
DispatchQueue.main.async(execute: {() -> Void
in
itemimage.image = UIImage(data: data!)!
})
}).resume()
}
if let description = cell.textview_description {
description.text = itemimage_detail
}
if let view = cell.view_description {
view.isHidden = true
}
return cell
}
}
我上傳我的numberOfItemsInSection,請檢查。謝謝 –
我以前遇到過這個問題。你還可以發佈你的tableview委託功能?在我的情況下,我沒有爲表視圖單元格中的集合視圖設置數據源和委託屬性。 – Abhishek729