Here i am trying highlight the UICollectionViewCell on selection as shown in the image.I tried adding the border to the selected cell and the border comes inside the cell content view. Here is my try:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = priorityCollectionView.cellForItem(at: indexPath) as? BCPriorityListCollectionViewCell
let borderWidth: CGFloat = 6
cell?.contentView.frame = (cell?.labelBackground.frame.insetBy(dx: +borderWidth, dy: +borderWidth))!
cell?.contentView.layer.borderColor = cell?.backgroundColor?.cgColor
cell?.contentView.layer.borderWidth = borderWidth
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = priorityCollectionView.cellForItem(at: indexPath) as? BCPriorityListCollectionViewCell
let borderWidth: CGFloat = 0
cell?.contentView.frame = (cell?.labelBackground.frame.insetBy(dx: +borderWidth, dy: +borderWidth))!
cell?.contentView.layer.borderColor = UIColor.clear.cgColor
cell?.contentView.layer.borderWidth = borderWidth
}
How to do this?
Instead of adding the border width for the selected cell, just use transformation scale for zooming the selected cell. Write this code in didSelect:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedCell = priorityCollectionView.cellForItem(at: indexPath) as? BCPriorityListCollectionViewCell
priorityCollectionView.bringSubview(toFront: selectedCell!)
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 5, initialSpringVelocity: 0, options: [], animations: {
selectedCell?.transform = CGAffineTransform(scaleX: 1.2, y: 2)
})
}
And in didDeselect:
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let unselectedCell = priorityCollectionView.cellForItem(at: indexPath) as? BCPriorityListCollectionViewCell
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 5, initialSpringVelocity: 0, options: [], animations: {
unselectedCell?.transform = .identity
})
}
Result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With