gpt4 book ai didi

ios - 有附加内容时 ScrollView 顶部/底部的渐变

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:49 25 4
gpt4 key购买 nike

我有一个 scrollview>ContentView>TextLabel 设置,其中显示了渐变,但没有按照我想要的方式工作。这是一个清晰的背景 scrollView,所以我要找的只是文本上的清晰渐变蒙版。我 found something类似于我在 Objective-C 中寻找的,但该线程没有 Swift 解决方案。

我的最终目标似乎是大多数人可能会使用的东西,所以我很惊讶还没有 Swift 版本。我尝试编码的功能是:

  1. 有时文本会完全适合 scrollView 的固定大小,因此不应该有渐变。
  2. 当文本长于无法容纳并且其中一些文本低于 scrollView 的底部截断线时, View 的底部应该淡入淡出以清除。
  3. 一旦用户向下滚动并且顶部应该淡出,表明上面还有更多内容。

我试过这段代码来处理项目符号#2:

        let gradient = CAGradientLayer()
gradient.frame = self.bio_ScrollView.superview!.bounds ?? CGRectNull
gradient.colors = [UIColor.whiteColor().CGColor, UIColor.clearColor().CGColor]
//gradient.locations = [0, 0.15, 0.25, 0.75, 0.85, 1.0]
gradient.locations = [0.6, 1.0]
self.bio_ScrollView.superview!.layer.mask = gradient

但是它会淡出所有内容,包括它下面的按钮,它显然不在 ScrollView 中:

scrollView with gradient

如果我删除 .superview 并将其直接应用于 scrollView,它只会淡化可见初始部分下方的所有文本:

scrollview gradient not working

有人知道如何正确实现吗?

最佳答案

想通了。首先,确保您添加了正确的 View 层次结构。 ScrollView 需要嵌入到容器 View 中(这是应用渐变的对象):

Gradient View Hierarchy

  1. 顶部/容器 View :根据需要进行设置
  2. ScrollView :将所有边固定到容器(总共 4 个约束)
  3. ScrollView 内容 View :固定边缘 + 中心 X(总共 5 个约束)
  4. 标签:固定边(总共 4 个约束)

将“scrollViewDelegate”添加到 ViewController 类:

class ViewController_WithScrollView: UIViewController, UIScrollViewDelegate {
....

将上面列出的四个 View 与 IBOutlets 连接起来。然后,在 viewDidLoad 中设置您的 scrollView 委托(delegate):

override func viewDidLoad() {
super.viewDidLoad()

yourScrollView.delegate = self
//+All your other viewDidLoad stuff
}

然后实现 scrollViewDidScroll 函数,由于您在上面所做的工作,它将自动运行。

func scrollViewDidScroll (scrollView: UIScrollView) {
if scrollView.isAtTop {
self.applyGradient_To("Bot")
} else if scrollView.isAtBottom {
self.applyGradient_To("Top")
} else {
self.applyGradient_To("Both")
}
}

然后添加这个神奇的渐变代码:

func applyGradient_To (state: String) {
let gradient = CAGradientLayer()
gradient.frame = self.yourScrollView.superview!.bounds ?? CGRectNull

switch state {
case "Top":
gradient.colors = [UIColor.clearColor().CGColor,UIColor.whiteColor().CGColor]
gradient.locations = [0.0,0.2]
case "Bot":
gradient.colors = [UIColor.whiteColor().CGColor, UIColor.clearColor().CGColor]
gradient.locations = [0.8,1.0]
default:
gradient.colors = [UIColor.clearColor().CGColor,UIColor.whiteColor().CGColor,UIColor.whiteColor().CGColor, UIColor.clearColor().CGColor]
gradient.locations = [0.0,0.2,0.8,1.0]
}
self.yourScrollView.superview!.layer.mask = nil
self.yourScrollView.superview!.layer.mask = gradient
}

应该可以的!

关于ios - 有附加内容时 ScrollView 顶部/底部的渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38376638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com