У меня есть коллекцияView с тремя разделами и кнопкой на заголовке, чтобы удалить каждый раздел. Я написал свой код, но я продолжаю получать эту ошибку:Кнопка удаления не работает, collectionView
fatal error: Index out of range (lldb)
Но я не уверен, что происходит? Почему это не работает.
Это мой код:
//Global Identifier
private let cellIdentifier = "ImageCell"
private let headerIdentifier = "Header"
class ViewController: UICollectionViewController {
//Data Models
//Image Arrays
var fireImages: [UIImage] = [
UIImage(named: "charizard")!,
UIImage(named: "ninetails")!,
UIImage(named: "arcanine")!,
UIImage(named: "rapidash")!,
UIImage(named: "magmar")!,
UIImage(named: "flareon")!
]
var waterImages: [UIImage] = [
UIImage(named: "blastoise")!,
UIImage(named: "golduck")!,
UIImage(named: "cloyster")!,
UIImage(named: "goldeen")!,
UIImage(named: "magikarp")!,
UIImage(named: "vaporeon")!
]
var electricImages: [UIImage] = [
UIImage(named: "pikachu")!,
UIImage(named: "magneton")!,
UIImage(named: "zapdos")!,
UIImage(named: "electabuzz")!,
UIImage(named: "raichu")!,
UIImage(named: "jolteon")!
]
//Name Arrays
var fireNames = ["Charizard", "Ninetales", "Arcanine", "Rapidash", "Magmar", "Flareon"]
var waterNames = ["Blastoise", "Golduck", "Cloyster", "Goldeen", "Magikarp", "Vaporeon"]
var electricNames = ["Pikachu", "Magneton", "Zapdos", "Electrabuzz", "Raichu", "Jolteon"]
//Sections
var sectionTitle = ["Fire Types", "Water Types", "Electric Types"]
//--------------------------------
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//--------------------------------
//MARK: - UICollectionViewDataSource
//Number of Sections
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return sectionTitle.count
}
//Number of Cells in each Section
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//How can I dynamically code this area?
return 6
}
//Header Configuration
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if indexPath.section == 0 {
//Fire Type header
let header = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier, forIndexPath: indexPath) as! CollectionReusableView
header.headerTitle.text = sectionTitle[indexPath.section]
header.backgroundColor = UIColor.orangeColor()
header.deleteButton.tag = indexPath.section
return header
} else if indexPath.section == 1 {
//Water Type header
let header = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier, forIndexPath: indexPath) as! CollectionReusableView
header.headerTitle.text = sectionTitle[indexPath.section]
header.backgroundColor = UIColor.cyanColor()
header.deleteButton.tag = indexPath.section
return header
} else {
//Electric Type header
let header = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier, forIndexPath: indexPath) as! CollectionReusableView
header.headerTitle.text = sectionTitle[indexPath.section]
header.backgroundColor = UIColor.yellowColor()
header.deleteButton.tag = indexPath.section
return header
}
}
//Cell Configuration
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
//Fire Type cells
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.pokemonImage.image = fireImages[indexPath.row]
cell.pokemonLabel.text = fireNames[indexPath.row]
return cell
} else if indexPath.section == 1 {
//Water Type cells
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.pokemonImage.image = waterImages[indexPath.row]
cell.pokemonLabel.text = waterNames[indexPath.row]
return cell
} else {
//Electric Type cells
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.pokemonImage.image = electricImages[indexPath.row]
cell.pokemonLabel.text = electricNames[indexPath.row]
return cell
}
}
//Delete Section Button
@IBAction func deleteSectionButton(sender: UIButton) {
//Section tag
let section = sender.tag
if section == 0 {
//Update data model
fireImages.removeAtIndex(section)
fireNames.removeAtIndex(section)
sectionTitle.removeAtIndex(section)
//Action
collectionView?.performBatchUpdates({
self.collectionView?.deleteSections(NSIndexSet(index: section))
},
completion: { (finished) in
if finished {
self.collectionView!.reloadData()
}
})
} else if section == 1 {
//Update data model
waterImages.removeAtIndex(section)
waterNames.removeAtIndex(section)
sectionTitle.removeAtIndex(section)
//Action
collectionView?.performBatchUpdates({
self.collectionView?.deleteSections(NSIndexSet(index: section))
},
completion: { (finished) in
if finished {
self.collectionView!.reloadData()
}
})
} else {
//Update data model
electricImages.removeAtIndex(section)
electricNames.removeAtIndex(section)
sectionTitle.removeAtIndex(section)
//Action
collectionView?.performBatchUpdates({
self.collectionView?.deleteSections(NSIndexSet(index: section))
},
completion: { (finished) in
if finished {
self.collectionView!.reloadData()
}
})
}
}
}
Это также показывает мне это.
Я мало знаю о представлениях коллекции, но кажется, что вы жестко кодируете 3 раздела в каждый файл коллекции, даже когда вы его удалили. – Shades
Как я могу динамически кодировать переопределение «numberOfItemsInSection»? Он говорит 6 прямо сейчас – art3mis
Я думаю, вы хотите изменить numberOfSectionsInCollectionView. Вместо 3 используйте sectionTitle.count, и когда вы удалите раздел, удалите его заголовок из массива. Конечно, так как я никогда не использовал их сам, я мог бы уйти. – Shades