Why do all backgrounds disappear on UITableViewCell select?

前端 未结 8 1883
南笙
南笙 2020-12-02 14:22

My current project\'s UITableViewCell behavior is baffling me. I have a fairly straightforward subclass of UITableViewCell. It adds a few extra elements to the base view (vi

8条回答
  •  再見小時候
    2020-12-02 15:01

    Having read through all the existing answers, came up with an elegant solution using Swift by only subclassing UITableViewCell.

    extension UIView {
        func iterateSubViews(block: ((view: UIView) -> Void)) {
            for subview in self.subviews {
                block(view: subview)
                subview.iterateSubViews(block)
            }
        }
    }
    
    class CustomTableViewCell: UITableViewCell {
       var keepSubViewsBackgroundColorOnSelection = false
    
        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
        }
    
        // MARK: Overrides
        override func setSelected(selected: Bool, animated: Bool) {
            if self.keepSubViewsBackgroundColorOnSelection {
                var bgColors = [UIView: UIColor]()
                self.contentView.iterateSubViews() { (view) in
    
                    guard let bgColor = view.backgroundColor else {
                        return
                    }
    
                    bgColors[view] = bgColor
                }
    
                super.setSelected(selected, animated: animated)
    
                for (view, backgroundColor) in bgColors {
                    view.backgroundColor = backgroundColor
                }
            } else {
                super.setSelected(selected, animated: animated)
            }
        }
    
        override func setHighlighted(highlighted: Bool, animated: Bool) {
            if self.keepSubViewsBackgroundColorOnSelection {
                var bgColors = [UIView: UIColor]()
                self.contentView.iterateSubViews() { (view) in
                    guard let bgColor = view.backgroundColor else {
                        return
                    }
    
                    bgColors[view] = bgColor
                }
    
                super.setHighlighted(highlighted, animated: animated)
    
                for (view, backgroundColor) in bgColors {
                    view.backgroundColor = backgroundColor
                }
            } else {
                super.setHighlighted(highlighted, animated: animated)
            }
        }
    }
    

提交回复
热议问题