2015-04-13 2 views
4

Прямо сейчас у меня есть список прокручиваемых имен пользователей, используя коллекцию View of buttons. Но я хотел бы добавить перекрывающиеся кнопки удаления в каждую строку. Они должны быть прикреплены к кнопкам имен и прокручивать их.Как добавить кнопку удаления в коллекцию View Cell в Swift?

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

User Selection Screen

Текущий код:

//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) 
    } 

    } 

ответ

10

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

  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

+0

Что такое 'UserSelectCollection'? – maidi

+1

'UserSelectCollection', скорее всего, его коллекция. – FunkyMonk91

+0

Привет, я добавил метод addTarget, но показывая ошибку. «Значение типа« UILabel »не имеет никакого« addTarget »участника.« Любой альтернативный способ сделать @Justin Lewis –

1

Почему бы не создавать пользовательские UICollectionViewCell в IB и просто добавить кнопку к нему? зарегистрировать его в CollectionView с:

- registerNib:forCellReuseIdentifier: 

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