2015-06-04 4 views
1
  • Swift, без раскадровки, UICollectionView из XIb файла

Я бегу очень простой код, чтобы обновить цвет фона ячейки, но, более одной клетки обновляют.UICollectionView didSelectItemAtIndexPath эффекты несколько ячеек - быстрые

 override func viewDidLoad(){ 
    super.viewDidLoad() 
    // getting images from library 
    images = PHAsset.fetchAssetsWithMediaType(.Image, options: nil) 

    collectionView.allowsMultipleSelection = false 
    var nipName2 = UINib(nibName: "CollectionViewCell", bundle:nil) 
    collectionView.registerNib(nipName2, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderCell") 
    var nipName = UINib(nibName: "MyViewCell", bundle:nil) 
    collectionView.registerNib(nipName, forCellWithReuseIdentifier: "Cell") 
} 

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { 
    return 1 
} 

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return images.count 
} 

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ 
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyViewCell 
    cell.frame.size.width = 60 
    return cell 
} 

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView{ 
    switch kind 
    { 
    case UICollectionElementKindSectionHeader: 
     let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "HeaderCell", forIndexPath: indexPath) as! CollectionViewCell 
     return headerView 
    default: 
     assert(false, "Unexpected element kind") 
    } 
} 

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
{ 
    var cell = collectionView.cellForItemAtIndexPath(indexPath) 
    cell?.backgroundColor = UIColor.redColor() 
} 

У меня около 300 различных ячеек. Я хочу обновить только третье, но случайное изменение фона многих других ячеек.

+0

Я бы предложил переопределить 'setSelected: animated:' вашего 'UICollectionViewCell'. – Larme

+0

Вы разрешаете множественный выбор в 'UICollectionView'? –

+0

- «collectionView.multipleTouchEnabled = false» не работает, если это то, что вы имеете в виду. - «collectionView.allowsMultipleSelection = false» также не работает. – fatihyildizhan

ответ

2

Таким образом, сбор и просмотр таблиц имеют прочную концепцию повторного использования вида. Это позволяет добиться больших приростов производительности, так как в то же время не нужно хранить [в вашем случае] 300 ячеек памяти.

Когда вы устанавливаете цвет фона в некоторых ячейках, эти ячейки могут повторно использоваться при прокрутке. Поскольку вы явно не устанавливаете фон при просмотре представления, он просто использует то, что в настоящее время есть.

Чтобы исправить это просто установить цвет, когда представление запрашивается:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ 
    // This does not guarantee to be a fresh, new cell, can be reused 
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyViewCell 
    cell.frame.size.width = 60 
    // Explicitly set the background color: 
    cell.backgroundColor = .whiteColor() // or whatever your default color is 
    return cell 
} 

Теперь, очевидно, это вызовет дополнительные побочные эффекты. Скажем, вы меняете цвет фона ячейки на красный и прокручиваете прочь. Когда вы вернетесь, вы снова установите его на белый. При этом вам нужно отслеживать, какие ячейки (возможно, путем хранения их индексов) выбраны и соответствующим образом настроили их цвет.

+0

спасибо, это сработало – fatihyildizhan

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