Minebomber
Minebomber

Reputation: 1211

How do I select and highlight a UICollectionView like a UITableViewCell?

I have a simple dilemma. I have a UICollectionViewController in my app that displays saved quizzes. I have the loading right, but I want it to move detect a tap on one of them and then do logic to load it into the main VC. I would like the selection to be similar to a UITableViewCell where it highlights it for a second and then unhighlights it. I am using a subclassed UICollectionViewCell if that helps.

Upvotes: 6

Views: 2135

Answers (3)

Nicolas Miari
Nicolas Miari

Reputation: 16256

In order for the highlighting to show, you can subclass your cells like this:

import UIKit

class CustomCell: UICollectionViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()

        let backgroundView = UIView(frame: CGRectZero)

        backgroundView.backgroundColor = UIColor.blueColor()

        self.selectedBackgroundView = backgroundView
    }
}

From the docs for UICollectionViewCell:

You can use this view to give the cell a custom appearance when it is selected. When the cell is selected, this view is layered above the backgroundView and behind the contentView.

Upvotes: 5

luckyShubhra
luckyShubhra

Reputation: 2751

Unlike UITableView, in UICollectionView there is no specific method defined to do so. U need to implement it programmatically by changing its background colour or background image of the specific cell for instant. U can refer Apple Documentation.https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionView_class/ Hope it helps.

*****EDITED***** You can refer this ans too.. Why UICollectionView's UICollectionViewCell is not highlighting on user touch? Happy Coding.. :)

Upvotes: 0

Sneha
Sneha

Reputation: 1444

UICollectionViewCell has a property

@property(nonatomic, getter=isHighlighted) BOOL highlighted;

You can use this property for selecting the UICollectionViewCell in cellForItemAtIndexPath:

Upvotes: 0

Related Questions