【发布时间】:2020-09-10 00:48:07
【问题描述】:
当用户单击按钮时,它会随机化用于在大圆圈中创建渐变的颜色。在它下面是两个小圆圈,显示用于渐变的纯色。它们在开始时都正确显示(主圆圈是随机小圆圈颜色的渐变)但是当我点击按钮时,只有小圆圈改变颜色;大圆圈保持相同的渐变颜色。
扩展和视图控制器:
extension UIView {
func setupGradientBackground(colorOne: UIColor, colorTwo: UIColor) {
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, at: 0)
}
}
extension UIColor {
static var random: UIColor {
return UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0)
}
}
class GradientController: UIViewController {
let gradientView = GradientView()
let leftGradientColor: UIColor = .random
let rightGradientColor: UIColor = .random
}
override func viewDidLoad() {
super.viewDidLoad()
view = gradientView
newGradient()
}
func newGradient() {
gradientView.mainCircleView.setupGradientBackground(colorOne: leftGradientColor, colorTwo: rightGradientColor)
gradientView.colorCircleLeftView.backgroundColor = leftGradientColor
gradientView.colorCircleRightView.backgroundColor = rightGradientColor
gradientView.gradientGenerateButton.addTarget(self, action: #selector(randomGradient(sender:)), for: .touchUpInside)
}
@objc func randomGradient(sender: UIButton)
{
let leftGradient = UIColor.random
let rightGradient = UIColor.random
gradientView.colorCircleLeftView.backgroundColor = leftGradient
gradientView.colorCircleRightView.backgroundColor = rightGradient
//Here is where it's not changing colors. Doesn't seem like the VC recognizes it in this function
gradientView.mainCircleView.setupGradientBackground(colorOne: leftGradient, colorTwo: rightGradient)
}
查看:
class GradientView: UIView {
//circle's UIView code in Extensions
let mainCircleView = UIView().circleView(width: 380, height: 380)
let colorCircleLeftView = UIView().circleView(width: 40, height: 40)
let colorCircleRightView = UIView().circleView(width: 40, height: 40)
...
func setupLayout() {
...
}
}
我尝试将 mainCircleView 颜色更改为纯 UIColors,例如 gradientView.mainCircleView.setupGradientBackground(colorOne: .red, colorTwo: .orange) 以查看主 Circle 是否更改为 func newGradient() 和 @objc func randomGradient(sender: UIButton) 中的这些颜色。它只会在func newGradient() 中更改我手动设置的内容,因此这意味着 VC 无法识别@objc func 中的主 Circle,但我不知道如何修复它...
感谢任何帮助!
【问题讨论】:
-
你到底想在这里实现什么?
-
如果您可以共享完整代码或可以运行以重现问题的代码的最小版本,这将有助于提供具体的答案。
标签: ios swift cagradientlayer