How to mask UITableViewCells underneath a UITableView Transparent Header

后端 未结 10 1940
后悔当初
后悔当初 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:54

    The Swift 3 version didn't work for me because I added the UITableViewController as a subview. So I had to make some changes in the extension of the scrollview.

    This should also work with UITableViewController that have been pushed from another ViewController (Note: not tested)

    extension NavNotitionTableViewController {
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        for cell in tableView.visibleCells {
    
            let calculatedY = cell.frame.origin.y - scrollView.contentOffset.y;
            if let customCell = cell as? NavNotitionTableViewCell {
    
                if(calculatedY < 44 && calculatedY > 0){
                    let hideAmount = 44 - calculatedY;
    
                    if let customCell = cell as? NavNotitionTableViewCell {
                        customCell.maskCell(fromTop: hideAmount)
                    }
                }else if (calculatedY > 0){
                    //All other cells
                    customCell.maskCell(fromTop: 0)
                }else if (calculatedY < 0){
                    customCell.maskCell(fromTop: cell.frame.height);
                }
            }
        }
    }
    }
    

    In this example, I first get the frame Y origin of the cell and distract the scollViews contentOffsetY.

    The height of my custom section is 44. So I define the hideAmount value for the mask.

    The Cell functions are untouched:

    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
    }
    

提交回复
热议问题