Fade edges of UITableView

后端 未结 4 1919
情深已故
情深已故 2020-12-05 09:20

I\'ve made a little research about my problem and unfortunately there was no solution for my problem. The closest was Fade UIImageView as it approaches the edges of a UIScro

4条回答
  •  失恋的感觉
    2020-12-05 09:36

    Swift version of @victorfigol's excellent solution:

    class FadingTableView : UITableView {
      var percent = Float(0.05)
    
      private let outerColor = UIColor(white: 1.0, alpha: 0.0).cgColor
      private let innerColor = UIColor(white: 1.0, alpha: 1.0).cgColor
    
      override func awakeFromNib() {
        super.awakeFromNib()
        addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
      }
    
      override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if object is FadingTableView && keyPath == "bounds" {
            initMask()
        }
      }
    
      deinit {
        removeObserver(self, forKeyPath:"bounds")
      }
    
      override func layoutSubviews() {
        super.layoutSubviews()
        updateMask()
      }
    
      func initMask() {
        let maskLayer = CAGradientLayer()
        maskLayer.locations = [0.0, NSNumber(value: percent), NSNumber(value:1 - percent), 1.0]
        maskLayer.bounds = CGRect(x:0, y:0, width:frame.size.width, height:frame.size.height)
        maskLayer.anchorPoint = CGPoint.zero
        self.layer.mask = maskLayer
    
        updateMask()
      }
    
      func updateMask() {
        let scrollView : UIScrollView = self
    
        var colors = [CGColor]()
    
        if scrollView.contentOffset.y <= -scrollView.contentInset.top { // top
            colors = [innerColor, innerColor, innerColor, outerColor]
        }
        else if (scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height { // bottom
            colors = [outerColor, innerColor, innerColor, innerColor]
        }
        else {
            colors = [outerColor, innerColor, innerColor, outerColor]
        }
    
        if let mask = scrollView.layer.mask as? CAGradientLayer {
            mask.colors = colors
    
            CATransaction.begin()
            CATransaction.setDisableActions(true)
            mask.position = CGPoint(x: 0.0, y: scrollView.contentOffset.y)
            CATransaction.commit()
         }
      }
    }
    

提交回复
热议问题