How can I highlight selected UICollectionView cells? (Swift)
you can use border change on didSelectItemAtIndexPath
override event like the below code and assign new settings on the cell.
Swift 3.x:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
addToList.append(objectsArray[indexPath.row])
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderWidth = 2.0
cell?.layer.borderColor = UIColor.gray.cgColor
}
Here is my solution, and I'm sure it works.
My solution includes 3 highlight effects, UICollectionCell
's selectedBackgroundView
, cell.contentView.backgroundColor
, or your your own specialHighlightedArea
; just feel free to choose the one you need, and feel free to add more effects as your App's Designer requires.
How to use? Just inherit BaseCollectionViewCell
. If needed, configure in cell's init
or collectionView
's delegate methods.
If you don't need highlight effect, just find a method named 'shouldHighlightItemAtIndexPath' in UICollectionViewDelegate and return false
or just set cell.shouldTintBackgroundWhenSelected = false
.
extension UIColor {
convenience init(rgb: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgb & 0xFF00) >> 8) / 255.0, blue: CGFloat(rgb & 0xFF) / 255.0, alpha: alpha)
}
}
/// same with UITableViewCell's selected backgroundColor
private let cellHighlightedColor = UIColor(rgb: 0xD8D8D8)
class BaseCollectionViewCell: UICollectionViewCell {
var shouldTintBackgroundWhenSelected = true // You can change default value
var specialHighlightedArea: UIView?
// make lightgray background show immediately(on touch)
// (使灰背景在手指触到 cell 时立即出现)
override var isHighlighted: Bool {
willSet {
onSelected(newValue)
}
}
// keep lightGray background from selected until unselected
// (保留灰背景直至取消选中)
override var isSelected: Bool {
willSet {
onSelected(newValue)
}
}
func onSelected(_ newValue: Bool) {
// selectedBackgroundView is defined by UICollectionViewCell
guard selectedBackgroundView == nil else { return }
if shouldTintBackgroundWhenSelected {
contentView.backgroundColor = newValue ? cellHighlightedColor : UIColor.clear
}
if let sa = specialHighlightedArea {
sa.backgroundColor = newValue ? UIColor.black.withAlphaComponent(0.4) : UIColor.clear
}
}
}