ios - Swift:UIView 的背景渐变
问题描述
我在尝试将渐变背景添加到 UIView
. 我做了一个extension
并UIView
添加了以下方法:
func setGradientBackground(colorTop: UIColor, colorBottom: UIColor) {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.frame = bounds
layer.insertSublayer(gradientLayer, at: 0)
}
然后我打电话:
separatorView.setGradientBackground(colorTop: .clear, colorBottom: .red)
但它不起作用。视图已呈现,但其背景完全清晰。我也试过了CGColor
解决方案
有2个问题:
我需要设置起点和终点以提供渐变方向:
func setGradientBackground(colorTop: UIColor, colorBottom: UIColor) { let gradientLayer = CAGradientLayer() gradientLayer.colors = [colorBottom.cgColor, colorTop.cgColor] gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0) gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0) gradientLayer.locations = [0, 1] gradientLayer.frame = bounds layer.insertSublayer(gradientLayer, at: 0) }
第二个问题是
CAGradientLayer
视图布局后生效。我解决了这个setGradientBackground()
问题viewDidAppear
:override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) separatorView.setGradientBackground(colorTop: .clear, colorBottom: Colors.darkGrey) }
推荐阅读
- javascript - 如何在浏览器中获取 Google Drive API 应用程序特定数据?
- kivy - 如何为我的 kivy 应用程序做出正确的解决方案?
- c++ - 复杂模板类型名称的别名
- javascript - 在 CSS 中更改选择的颜色
- python - 运行python文件时未找到应用程序错误
- javascript - 如何使用 react-bootstrap table-2 将列中的值显示为链接?
- javascript - 通过js获取当前滚动位置的值
- jquery-ui - Jquery UI Datepicker 使用 dateFormat dd.mm.yy 设置默认值
- typescript - TypeScript 自定义类型提示
- javascript - 使用打字稿的正确方法?