Change Background of UICollectionView Cell on Tap

后端 未结 6 905
时光说笑
时光说笑 2020-12-08 04:13

I have a UICollectionView that I have created programmatically. I would like for the collection view to behave in the following way:

1. User touches cell
2.          


        
6条回答
  •  悲&欢浪女
    2020-12-08 05:02

    Here is my solution. And I'm sure it really works.
    I provide three methods to highlight a cell (selectedBackgroundView, tint cell.contentView and tint a special area).

    How to use:
    1. just inherit BaseCollectionViewCell and do nothing;
    2. inherit and set specialHighlightedArea = UIView(), and contentView.addSubView(specialHighlightedArea), then layout it or add constraint to use Auto Layout;
    3. if you don't need highlight effect, just write a method named 'shouldHighlightItemAtIndexPath' defined by UICollectionViewDelegate and make it return false, or set cell.shouldTintBackgroundWhenSelected = false and set specialHighlightedArea = nil and remove it from superView.

    /// same with UITableViewCell's selected backgroundColor
    private let highlightedColor = UIColor(rgb: 0xD8D8D8) 
    
    /// you can make all your collectionViewCell inherit BaseCollectionViewCell
    class BaseCollectionViewCell: UICollectionViewCell {
    
        /// change it as you wish when or after initializing
        var shouldTintBackgroundWhenSelected = true
    
        /// you can give a special view when selected
        var specialHighlightedArea: UIView? 
    
        // make lightgray background display immediately(使灰背景立即出现)
        override var isHighlighted: Bool { 
            willSet {
                onSelected(newValue)
            }
        }
    
        // keep lightGray background until unselected (保留灰背景)
        override var isSelected: Bool { 
            willSet {
                onSelected(newValue)
            }
        }
    
        func onSelected(_ newValue: Bool) {
            guard selectedBackgroundView == nil else { return }
            if shouldTintBackgroundWhenSelected {
                contentView.backgroundColor = newValue ? highlightedColor : UIColor.clear
            }
            if let area = specialHighlightedArea {
                area.backgroundColor = newValue ? UIColor.black.withAlphaComponent(0.4) : UIColor.clear
            }
        }
    }
    
    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)
        }
    }
    

提交回复
热议问题