How to mask UITableViewCells underneath a UITableView Transparent Header

后端 未结 10 1945
后悔当初
后悔当初 2020-12-08 07:29

I want the header to mask the cells, but not the background.

I have a UITableView with transparent headers and cells similar to Apple\'s Notification Center (when yo

10条回答
  •  星月不相逢
    2020-12-08 07:56

    Clean Swift 3 Version:

    extension YourViewController: UIScrollViewDelegate {
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            for cell in tableView.visibleCells {
                let hiddenFrameHeight = scrollView.contentOffset.y + navigationController!.navigationBar.frame.size.height - cell.frame.origin.y
                if (hiddenFrameHeight >= 0 || hiddenFrameHeight <= cell.frame.size.height) {
                    if let customCell = cell as? CustomCell {
                        customCell.maskCell(fromTop: hiddenFrameHeight)
                    }
                }
            }
        }
    }
    
    class CustomCell: UITableViewCell {
        public func maskCell(fromTop margin: CGFloat) {
            layer.mask = visibilityMask(withLocation: margin / frame.size.height)
            layer.masksToBounds = true
        }
    
        private func visibilityMask(withLocation location: CGFloat) -> CAGradientLayer {
            let mask = CAGradientLayer()
            mask.frame = bounds
            mask.colors = [UIColor.white.withAlphaComponent(0).cgColor, UIColor.white.cgColor]
            let num = location as NSNumber
            mask.locations = [num, num]
            return mask
        }
    }
    

    I just used this and it works like a charm. I want to thank everyone in the post! Up votes all around!

提交回复
热议问题