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: 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 只是为了确定,但没有成功。

回顾:

  1. 为什么背景颜色可以正常工作,但渐变却不行?
  2. 是否有更好的方法来调整 zPosition 以阻止它阻止对 UI 的访问?

最佳答案

CAGradientLayer.colors 需要一个 CGColor 数组,但您传递给它的是 UIColor相反。要修复它,请传递 UIColorCGColor 版本:

gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor]

出于某种原因,.colors 被声明为 [Any] 类型,因此编译器允许它通过,但最终得到一个空白渐变。

关于ios - Swift - 将渐变设置为 UITableView 部分背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035841/

相关文章:

ios - 在 XCode 4.6 中使用 Subversion

ios - xcode 属性检查器文本值未正确显示(文本太长)

ios - Swift 3 - 每次添加位置坐标时 UIView 都会加载

ios - 分组的 UITableView 35 点/像素顶部插图/填充

ios - 引用同一 View 的多个 UITableViewCell 单元 accessoryView 失败

iphone - Autorelease 上的自定义 UITableViewCell 导致应用程序崩溃

ios - 未安装应用程序时启动 Web 应用程序

ios - 使用 CoreMotion/Accelerometer 以编程方式检测 iPhone 是否掉落

ios - 无法将从相机拍摄的图像传递到另一个 View Controller

ios - 有没有办法将 segue 操作延迟到用户通过他们的照片库选择图像或拍照之后? swift