【发布时间】:2019-04-22 10:29:03
【问题描述】:
我查看了很多其他类似问题的答案,但似乎没有一个答案能解决我的问题,所以寻求一点帮助。
我正在尝试对 UIButton 应用垂直渐变,但渐变层并未显示在我的视图中。以下是相关代码:
let darkPurple = UIColor(displayP3Red: 61.0/255.0, green: 3.0/255.0, blue: 110.0/255.0, alpha: 1.0)
let lightPurple = UIColor(displayP3Red: 90.0/255.0, green: 32.0/255.0, blue: 130.0/255.0, alpha: 1.0)
let addButton = UIButton(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
addButton.title = "Start counting"
addButton.layer.cornerRadius = 30.0
addButton.layer.borderWidth = 1.0
addButton.layer.borderColor = darkPurple.cgColor
addButton.translatesAutoresizingMaskIntoConstraints = false
myView.addSubview(addButton)
addButton.applyGradient(with: [lightPurple, darkPurple], gradientOrientation: .vertical)
...以及应用渐变的代码:
typealias GradientPoints = (startPoint: CGPoint, endPoint: CGPoint)
enum GradientOrientation {
case topRightBottomLeft
case topLeftBottomRight
case horizontal
case vertical
var startPoint: CGPoint {
return points.startPoint
}
var endPoint: CGPoint {
return points.endPoint
}
var points: GradientPoints {
switch self {
case .topRightBottomLeft:
return (CGPoint(x: 0.0, y: 1.0), CGPoint(x: 1.0, y: 0.0))
case .topLeftBottomRight:
return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 1.0, y: 1.0))
case .horizontal:
return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 1.0, y: 0.0))
case .vertical:
return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.0, y: 1.0))
}
}
}
extension UIView {
func applyGradient(with colors: [UIColor], gradientOrientation orientation: GradientOrientation) {
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = colors.map { $0.cgColor }
gradient.startPoint = orientation.startPoint
gradient.endPoint = orientation.endPoint
gradient.borderColor = self.layer.borderColor
gradient.borderWidth = self.layer.borderWidth
gradient.cornerRadius = self.layer.cornerRadius
gradient.masksToBounds = true
gradient.isHidden = false
self.layer.insertSublayer(gradient, at: 0)
}
}
这是我得到的: empty button
感谢您的帮助!
【问题讨论】:
标签: ios swift xcode uibutton cagradientlayer