Ios Swift-将渐变设置为UITableView剖面背景
这就是我目前拥有的:Ios Swift-将渐变设置为UITableView剖面背景,ios,swift,uitableview,Ios,Swift,Uitableview,这就是我目前拥有的: 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: currentS
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
,并在点击标题时更改新节的索引。这是一个手风琴桌面视图,因此一次最多只能看到一个部分
由于某些原因,这不起作用,我不确定梯度代码中缺少了什么。我知道这是得到正确的帧,因为如果我注释掉渐变代码,并添加自己的背景色,它的工作非常好
另外,我将zPosition
设置为-1
。如果没有它,背景视图将覆盖整个视图。当它设置为-1
时,我可以看到视图的其余部分,但它仍然阻止用户交互。当我查看UI层次结构时,它将其显示在所有内容之上。有没有更好的方法可以通过编程将位置调整到低于其他位置?我试着将它设置为-1000
只是为了确定,但没有运气
重述:
为什么背景色效果很好,但渐变效果不好
是否有更好的方法来调整zPosition
以阻止其阻止对UI的访问
CAGradientLayer
的.colors
需要一个CGColor
s数组,但您要传递它UIColor
s。要修复此问题,请传递CGColor
版本的UIColor
s:
gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor]
由于某种原因,.colors
被声明为type[Any]
,因此编译器允许它通过,但最终会得到一个空白渐变。您应该使用CGColor
s而不是UIColor
s
gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor]
尽管参数是[Any]?
,但文档中说明:
定义每个渐变停止点颜色的CGColorRef
对象数组。可动画化
对于我问题的第二部分,这里是答案。删除addSubview
以及zPosition
,然后使用以下命令:
tableView.insertSubview(backgroundView, at: 0)