UIScrollView, showing that there is more data by f

2019-06-11 02:22发布

问题:

Is there a way to fade text at the bottom and top when there is more data to be scrolled through in the UIScrollView? Would I have to put something on top of the UILabel I have in the UIScrollView in order to get that effect?

回答1:

You can use a CAGradientLayer on both top and bottom. You can add/remove this in the delegate method scrollViewDidScroll: based on the scroll view's contentOffset.



回答2:

You can add an ImageView as a subview for scroll view with an transparent png in it.



回答3:

You can easily fade views in and out using Core Animation. See the Animations section of the View Programming Guide for iOS for an idea of what you can easily animate. There's even an example (Listing 4-1) of animating the alpha property.



回答4:

I tried implementing Deepak's suggestion in Swift.

I think it would be like this,

class MyViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var textView: UITextView! ///< the scrolling text
let gradientLayer = CAGradientLayer()
var yEnd : CGFloat = 1

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewDidLayoutSubviews() {
    yEnd = CGFloat(textView.bounds.height) / CGFloat(textView.contentSize.height)
    gradientLayer.frame = CGRect(x: 0, y: 0, width: textView.contentSize.width, height: textView.contentSize.height)
    gradientLayer.locations = [0, 0.2, 0.8, 1]
    gradientLayer.opaque = false
    gradientLayer.opacity = 1
    gradientLayer.startPoint = CGPoint(x: 0, y: 0)
    gradientLayer.endPoint = CGPoint(x: 0, y: yEnd)
    scrollOrigin = textView.bounds.origin.y
    // scroll to the top of the text. It will trigger scrollViewDidScroll
    textView.setContentOffset(CGPoint(x: 0,y: 0), animated: false)
    textView.layer.mask = gradientLayer
}

func scrollViewDidScroll(scrollView: UIScrollView) {
    // move the CALayer as we scroll, otherwise the fade will be scrolled away
    let lineHeight : CGFloat = 20
    let yOffset = CGFloat(scrollView.contentOffset.y) / CGFloat(scrollView.bounds.height)
    let yBottom = lineHeight - (textView.contentSize.height - scrollView.contentOffset.y - scrollView.bounds.height)
    gradientLayer.startPoint = CGPoint(x: 0, y: yOffset * yEnd)
    gradientLayer.endPoint = CGPoint(x: 0, y: (1 + yOffset) * yEnd)
    // change the alpha on top to fully visible on start of text
    let alphaTop = yOffset > 0 ? yOffset < 0.2 ? 5 * (0.2 - yOffset) : 0 : 1
    let alphaBottom = yBottom > 0 ? yBottom / lineHeight : 0
    gradientLayer.colors = [
        UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: alphaTop).CGColor,
        UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0).CGColor,
        UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0).CGColor,
        UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: alphaBottom).CGColor
    ]
}

}

The problem with this is that I see some delay in the gradient updates, so it's not completely smooth.