Is there a possibility to change the background color of UICollectionView
only while the element is tapped. I have tried:
-(void) collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
//change color when tapped
}
-(void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
//change back on touch up
}
But the result is that I can see the change only when i keep my finger for a bit longer time.
Is there some similar stuff like in UITableViewCell
method willSelectItemAtIndexPath:
?
But the result is that I can see the change only when i keep my finger for a bit longer time
The delay your are experiencing is probably related to the "Delay content touches" checkbox in the storyboard.
Try to un-check it.
I think you might want keep the selected cell with different background color, right?
Then try this code.
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor magentaColor];
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor cyanColor];
}
Just simply assign different BG color for cells in different status.
Additionally the code below is the documentation of sequence triggering methods while someone touches a collectionView cell. You can also find these documents in UICollectionView.h file, UICollectionViewDelegate protocol part.
// Methods for notification of selection/deselection and highlight/unhighlight events.
// The sequence of calls leading to selection from a user touch is:
//
// (when the touch begins)
// 1. -collectionView:shouldHighlightItemAtIndexPath:
// 2. -collectionView:didHighlightItemAtIndexPath:
//
// (when the touch lifts)
// 3. -collectionView:shouldSelectItemAtIndexPath: or -collectionView:shouldDeselectItemAtIndexPath:
// 4. -collectionView:didSelectItemAtIndexPath: or -collectionView:didDeselectItemAtIndexPath:
// 5. -collectionView:didUnhighlightItemAtIndexPath:
ios uicollectionview uicollectionviewdelegate
// In Swift
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! UICollectionViewCell
cell.backgroundColor = UIColor.magentaColor()
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! UICollectionViewCell
cell.backgroundColor = UIColor.cyanColor()
}