ios - 渐变不适用于由 Auto Layout Xcode Swift 定位的对象
问题描述
我正在尝试向视图添加渐变。然而,视图是使用自动布局定位的,因此渐变不能再应用于对象。我应该怎么办?
这是梯度函数:
func setGradientBackground() {
let gradient = CAGradientLayer()
gradient.frame = bounds
gradient.colors = [
UIColor(red: 143/255, green: 162/255, blue: 217/255, alpha:1).cgColor,
UIColor(red: 220/255, green: 141/255, blue: 129/255, alpha: 1).cgColor
]
gradient.locations = [0.0, 1.0]
gradient.startPoint = CGPoint(x:0, y:0)
gradient.endPoint = CGPoint(x:1, y:1)
layer.insertSublayer(gradient, at: 0)
}
这是添加对象的代码
let testView = UIView()
testView.setGradientBackground()
self.view.addSubview(testView)
testView.translatesAutoresizingMaskIntoConstraints = false
testView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
testView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
testView.heightAnchor.constraint(equalToConstant: 100).isActive = true
testView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
解决方案
推荐阅读
- c++ - 为什么当我明确告诉 Visual Studio 2019 创建一个 .hpp 文件时,它会创建一个 .h 文件?
- android - 将响应正文保存到 Android 上的存储
- blockchain - 用于区块链数据的 SubQuery vs TheGraph
- c - 从 Rust 调用 C 库给出“链接:致命错误 LNK1181:无法打开输入文件”
- c++ - 可以在目录 CMake 中使用整个项目的导入
- matlab - E(1,:)*c 和 E(1,:)*c(1,:) 有什么区别
- c# - Dotnet Sonar Scanner for ubuntu 错误“进程终止。找不到系统上安装的有效 ICU 包”
- java - Java Discord4j如何将消息发送到通道REST API?
- apache-flink - WatermarkGenerator#onEvent 方法签名中的 eventTimestamp 似乎是多余的
- android - 在 org.gradle.api.Project 类型的根项目“android”上找不到参数 [build_1c6nueis8xobld9$_run_closure2@7bfda345] 的方法 android()