2015-04-24 3 views
1

Я хочу, чтобы подсветка изменяла размер и внешний вид объекта внутри вида коллекции.Объекты CollectionView (Swift)

Как установить свойства объекта в ячейке просмотра коллекции в методе «didHighlight»?

В "cellForItemAtIndexPath" вы объявляете многоразовые клетки как класс

и просто использовать "cell.MyOutlet.backgroundColor = UIColor.blueColor()"

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
 
     
 
     if collectionView == self.CollectionViewController { 
 
      let (FriendFirstName,FriendLastName) = friends[indexPath.row] 
 
    
 
      let cell: CustomCellA = collectionView.dequeueReusableCellWithReuseIdentifier("demoCell", forIndexPath: indexPath) as! CustomCellA 
 
     
 
      if indexPath.section == 0 { 
 
       cell.cellTitle.text = Name 
 
       cell.imgCell.image = UIImage(named: Pics[indexPath.row]) 
 
      
 
       cell.imgCell.layer.masksToBounds = true 
 
       cell.self.imgCell.layer.cornerRadius = 20 
 
       
 
       return cell 
 
       
 
       
 
      } else { 
 
      
 
       let cell2: AddCell = collectionView.dequeueReusableCellWithReuseIdentifier("demoCell2", forIndexPath: indexPath) as! AddCell 
 
       return cell2 
 
      } 
 
     } else if collectionView == self.EmojiCollectionViewController { 
 
      let cellB: CustomCellB = collectionView.dequeueReusableCellWithReuseIdentifier("demoCellB", forIndexPath: indexPath) as! CustomCellB 
 
      
 
      cellB.MyLabel.text = arrayOne[indexPath.row] 
 
      
 
      return cellB 
 
      
 
     } else { 
 
      let cellC: CustomCellC = collectionView.dequeueReusableCellWithReuseIdentifier("demoCellC", forIndexPath: indexPath) as! CustomCellC 
 
      
 
      // ...Set up cell 
 
      let height = self.CollectionViewController2.frame.height 
 
      
 
      cellC.frame = CGRectMake(cellB.frame.origin.x, 0, cellB.frame.size.width, height) 
 
      cellC.updateConstraintsIfNeeded() 
 
      cellC.layoutIfNeeded() 
 
      cellC.imgVw.image = UIImage(named: pictures[indexPath.row] as! String) 
 

 
      return cellC 
 
     } 
 
     
 
    }

 
 
    func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) { 
 
     
 
     if collectionView == self.CollectionViewController { 
 
     
 
      if indexPath.section == 0 { 
 
       let cell: CustomCellA = CustomCellB() 
 
       cell.MyLabel.backgroundColor = UIColor.blueColor() //crashes due to nil value) 
 

 
      } 
 
     
 
     } else { 
 
      
 
      
 
     } 
 
     
 
     
 
    }

Я попытался использовать аналогичное определение в didHighlight, и он продолжает сбой.

ответ

0

Сначала вы должны определить collectionView Cell, а затем делать то, что вы хотите в этой ячейке. чтобы определить ваше надувательство добавить следующие строки в didHighlightItemAtIndexPath

if let cellToUpdate = self.dataCollection.cellForItemAtIndexPath(indexPath) { 
           //your code here. 
          } 
+0

это не открывает объекты для пользовательского класса. Мне нужно изменить рамку объекта внутри ячейки, когда ячейка подсвечивается. –

1

Пусть didHighlightItemAtIndexPath только изменения данных, а не просматривать. Итак, сделайте friends[indexPath.row] объект или добавьте еще один параметр в кортеж. И в didHighlightItemAtIndexPath сделать что-то вроде следующего:

if collectionView == self.CollectionViewController { 
    if indexPath.section == 0 { 
     let (fname, lname, color) = friends[indexPath.row]; 

     friends[indexPath.row] = (fname, lname, UIColor.blueColor()) 
    }  
} 

И в cellForItemAtIndexPath:

if collectionView == self.CollectionViewController { 
    let (FriendFirstName, FriendLastName, color) = friends[indexPath.row] 

    if indexPath.section != 0 { 
     let cell = collectionView.dequeueReusableCellWithReuseIdentifier("demoCell2", forIndexPath: indexPath) as! AddCell; 
     return cell; 
    } else if color == nil { 
     let cell = collectionView.dequeueReusableCellWithReuseIdentifier("demoCell", forIndexPath: indexPath) as! CustomCellA; 

     cell.cellTitle.text = Name 
     cell.imgCell.image = UIImage(named: Pics[indexPath.row]) 

     cell.imgCell.layer.masksToBounds = true 
     cell.self.imgCell.layer.cornerRadius = 20 

     return cell 
    } else { 
     cell = collectionView.dequeueReusableCellWithReuseIdentifier("demoCellB", forIndexPath: indexPath) as! CustomCellB; 

     // your code for CustomCellB 

     return cell; 
    } 

} 

EDIT: Обновление, поэтому вместо того, чтобы объекты, которые она использует кортежи. Также добавлена ​​необходимая функциональность. В принципе, вам нужно создать две прототипные ячейки в построителе интерфейса с различными идентификаторами и классами повторного использования. А затем удалите правильный идентификатор в пути индекса. Кроме того, я реструктурировать часть своего кода и, если бы я тебя, я бы создать другую функцию для каждого CollectionView и сделать что-то вроде:

if collectionView == self.CollectionViewController { 
    return self.dequeueCollectionCell(indexPath); 
} else if collectionView == self.EmojiCollectionViewController { 
    return self.dequeuEmojiCell(indexPath); 
} else { 
    return self.dequeueSomeOtherCell(indexPath); 
} 

Кроме того, код, который вы предоставили ... Я надеюсь, что это не является фактический производственный код, и вы изменили значения для этого форума. В противном случае, через пару дней, вы потеряете себя в том, что здесь происходит. Слишком много непоследовательных имен переменных и идентификаторов.

Еще один. Используйте соглашения об именах в именах классов. Прочтите это forum post для получения дополнительной информации. Apple использует camelCase везде. В большинстве случаев первая буква капитализируется для имен классов, а не для имен объектов.

+0

Проблема в том, что у меня есть UIView внутри ячейки collectionView. поскольку выход находится в отдельном классе, я не могу использовать cell.myView.backgroundColor, потому что я не могу его определить. –

+0

Также вы не можете установить цвет для строки или массива, то есть только для источника данных, а не для UILabel. –

+0

Я знаю, что вы не можете, поэтому я сказал, что заставляю друзей [indexPath.row] объекта или кортежа (я использовал объект) – Gasim

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