Как добавить кнопку удаления в ячейку представления коллекции в Swift?

Прямо сейчас у меня есть список прокручиваемых имен пользователей, использующих представление коллекции кнопок. Но я хотел бы добавить перекрывающиеся кнопки удаления в каждую строку. Их нужно будет прикрепить к кнопкам с именами и прокручивать вместе с ними.

Как я могу добавить эти кнопки в свой CollectionView? (Также я хотел бы пропустить кнопку удаления в первой строке по понятным причинам)

Экран выбора пользователя

Текущий код:

  //Add the cells to collection
  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: UsernameCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UsernameCollectionViewCell
    cell.usernameLabel.text = userNames [indexPath.row]
    return cell
  }

  //Upon Selecting an item
  func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    if (indexPath.row == 0){
      self.performSegueWithIdentifier("newUserSegue", sender: self)
    }
    else {
      sendData(userNames[indexPath.row])
      self.dismissViewControllerAnimated(true, completion: nil)
    }

  }

person Justin Lewis    schedule 13.04.2015    source источник


Ответы (2)


Получил работу! Вот как:

  1. Я добавил кнопку в ячейку в раскадровке.
  2. Подключил выход к классу UICollectionViewCell.
  3. Отредактированный код контроллера представления:

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
      let cell: UsernameCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UsernameCollectionViewCell
    
      cell.usernameLabel.text = userNames [indexPath.row]
    
      cell.deleteButton?.layer.setValue(indexPath.row, forKey: "index")
      cell.deleteButton?.addTarget(self, action: "deleteUser:", forControlEvents: UIControlEvents.TouchUpInside)
    
      // Remove the button from the first cell
      if (indexPath.row == 0){
        var close : UIButton = cell.viewWithTag(11) as! UIButton
        close.hidden = true
      }
    
      return cell
    }
    
    func deleteUser(sender:UIButton) {
    
      let i : Int = (sender.layer.valueForKey("index")) as! Int
      userNames.removeAtIndex(i)
      UserSelectCollection.reloadData()
    }
    

Большое спасибо JigarM за его примеры на GitHub: https://github.com/JigarM/UICollectionView-Swift

person Justin Lewis    schedule 13.04.2015
comment
Что такое UserSelectCollection? - person maidi; 28.11.2015
comment
UserSelectCollection, скорее всего, является выходом для просмотра его коллекции. - person FunkyMonk91; 27.02.2016
comment
Эй, я добавил метод addTarget, но показывает ошибку. Значение типа «UILabel» не имеет члена «addTarget», какой-либо альтернативный способ сделать @Justin Lewis - person shahin ali agharia; 14.07.2016
comment
Привет, друзья, не могли бы вы подсказать, как добавить программирование кнопки удаления в представлении коллекции? - person Saleem Khan; 17.01.2017

Почему бы не создать собственный UICollectionViewCell в IB и просто добавить к нему кнопку? Зарегистрируйте его в своем collectionView с помощью:

- registerNib:forCellReuseIdentifier:

Вы можете использовать делегат или уведомление для обработки нажатия кнопки.

person CryingHippo    schedule 13.04.2015