Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift-将渐变设置为UITableView剖面背景_Ios_Swift_Uitableview - Fatal编程技术网

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)