2016-08-14 1 views
1

У меня есть коллекция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() 
      } 
     }) 

    } 

} 

} 

Это также показывает мне это.

enter image description here

+0

Я мало знаю о представлениях коллекции, но кажется, что вы жестко кодируете 3 раздела в каждый файл коллекции, даже когда вы его удалили. – Shades

+0

Как я могу динамически кодировать переопределение «numberOfItemsInSection»? Он говорит 6 прямо сейчас – art3mis

+0

Я думаю, вы хотите изменить numberOfSectionsInCollectionView. Вместо 3 используйте sectionTitle.count, и когда вы удалите раздел, удалите его заголовок из массива. Конечно, так как я никогда не использовал их сам, я мог бы уйти. – Shades

ответ

1

Прежде всего, ваш код не что иное, как объектно-ориентированный. Вот некоторые проблемы:

  1. Вы жестко закодированное число ячеек в разделе: . Как вы справитесь со случаем, что типы классов pokemon имеют разное количество покемонов?
  2. В вашем коде много дубликатов, которых следует избегать. Есть много if section == элементов управления; что является четким показателем избежания принципов ОО.

В любом случае; поскольку у вас гораздо больше проблем, чем неработающая кнопка удаления; Я решил создать для вас чистый проект, чтобы показать, как подойти к проблеме более объектно-ориентированным способом. Я создал объекты домена, такие как Pokemon и PokemonClass, и сохранил соответствующие атрибуты внутри этих объектов. По этому пути; Я избегал много дублирования кода, существующих в вашем классе контроллера. Я также проиллюстрировал вам, как заставить кнопку удаления работать (кстати, нет надежных способов справиться с этим удалением функциональности раздела, но у меня нет достаточно времени для ее поиска, и я сделал это первым способом, который приходит на мой взгляд). Из-за ограничений времени я не занимался образами покемонов. Так или иначе; посмотрите исходный код, который я поделил на моем github repository. Вы можете задать любые вопросы, которые у вас есть, и вы, конечно, можете использовать любой код, который я предоставил. Надеюсь, это поможет вам начать дизайн в OO-стиле.

Смежные вопросы