首页 > 解决方案 > 渐变不适用于由 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

标签: iosswiftgradientios-autolayout

解决方案


推荐阅读