Xcode / Swift是新的,我在我的应用程序中的不同View Controllers中为一堆按钮添加了渐变层。我想知道是否有一种方法可以同时定位具有特定名称的所有按钮,而不是将我的代码单独添加到每个页面中。这是我的渐变代码:
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.btnSavePhoto.bounds
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha: 1.0).CGColor as CGColorRef
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha: 1.0).CGColor as CGColorRef
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.btnSavePhoto.layer.addSublayer(gradientLayer)
答案 0 :(得分:2)
您可以创建一个自定义类,使您的UIButton
以某种方式使用Gradient
适用于Swift 3
import UIKit
public class GradientButton: UIButton {
override public func layoutSubviews() {
super.layoutSubviews()
layoutGradientButtonLayer()
}
// MARK: Private
private func layoutGradientButtonLayer() {
let gradientLayer = CAGradientLayer()
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha: 1.0).cgColor as CGColor
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha: 1.0).cgColor as CGColor
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.layer.addSublayer(gradientLayer)
}
}
适用于Swift 2.3
import UIKit
public class GradientButton: UIButton {
override public func layoutSubviews() {
super.layoutSubviews()
layoutGradientButtonLayer()
}
// MARK: Private
private func layoutGradientButtonLayer() {
let gradientLayer = CAGradientLayer()
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha: 1.0).CGColor as CGColorRef
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha: 1.0).CGColor as CGColorRef
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.layer.addSublayer(gradientLayer)
}
}
然后在检查器for按钮中,您可以将Class设置为GradientButton检查图像
通过这种方式,您无需为渐变按钮编写代码。