这是我目前拥有的:
let topColor = UIColor(red: 2/255, green: 138/255, blue: 191/255, alpha: 1)
let bottomColor = UIColor(red: 1/255, green: 66/255, blue: 125/255, alpha: 1)
func configureGradient() {
let sectionRect = tableView.rect(forSection: currentSelectedIndex)
let backgroundView = UIView(frame: sectionRect)
backgroundView.layer.zPosition = -1
// backgroundView.backgroundColor = bottomColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [topColor, bottomColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.frame = sectionRect
backgroundView.layer.insertSublayer(gradientLayer, at: 0)
tableView.addSubview(backgroundView)
}
我在网络调用和 tableView.reloadData()
currentSelectedIndex
默认为 0
并在点击标题时更改为新部分的索引。这是一个 Accordion TableView ,因此一次最多只能显示一个部分。
出于某种原因,这不起作用,我不确定渐变代码中缺少什么。我知道它可以正确获取框架,因为如果我注释掉渐变代码并自行添加背景颜色,它就可以正常工作。
此外,我将 zPosition
设置为 -1
。如果没有它,backgroundView
会覆盖整个 View 。将它设置为 -1
我可以看到 View 的其余部分,但它仍然阻止用户交互。当我查看 UI 层次结构时,它显示在所有内容之上。有没有更好的方法以编程方式将位置调整为低于其他所有内容?我试过将它设置为 -1000
只是为了确定,但没有成功。
回顾:
- 为什么背景颜色可以正常工作,但渐变却不行?
- 是否有更好的方法来调整
zPosition
以阻止它阻止对 UI 的访问?
最佳答案
CAGradientLayer
的 .colors
需要一个 CGColor
数组,但您传递给它的是 UIColor
相反。要修复它,请传递 UIColor
的 CGColor
版本:
gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor]
出于某种原因,.colors
被声明为 [Any]
类型,因此编译器允许它通过,但最终得到一个空白渐变。
关于ios - Swift - 将渐变设置为 UITableView 部分背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035841/