声明新的按钮子类:
class GradientButton : UIButton {
var leftColor = UIColor.red
var rightColor = UIColor.green
var customImage : UIImage? {
didSet {
updateImageView()
}
}
let gradientLayer = CAGradientLayer()
let customImageView = UIImageView()
override var frame: CGRect {
didSet {
gradientLayer.frame = bounds
layer.layoutIfNeeded()
}
}
convenience init(leftColor: UIColor, rightColor: UIColor, image: UIImage) {
self.init()
self.leftColor = leftColor
self.rightColor = rightColor
customImage = image
updateImageView()
}
override init(frame: CGRect) {
super.init(frame: frame)
defaultInitializer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
defaultInitializer()
}
func defaultInitializer() {
gradientLayer.frame = bounds
gradientLayer.colors = [leftColor.cgColor, rightColor.cgColor]
gradientLayer.startPoint = CGPoint.init(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint.init(x: 1, y: 0.5)
layer.insertSublayer(gradientLayer, at: 0)
layer.layoutIfNeeded()
addSubview(customImageView)
customImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
func updateImageView() {
customImageView.image = customImage
customImageView.alpha = 0.2
layoutSubviews()
}
}
并且像这样初始化:
let rect = CGRect(x: 20, y: 20, width: 200, height: 100)
let button = GradientButton(leftColor: UIColor.red, rightColor: UIColor.cyan, image: UIImage(named: "1")!)
button.frame = rect
self.view.addSubview(button)
即使使用故事板也可以实现。
其他设置,如文本颜色、字体等,可以在UIButton声明中找到。 愉快的编码!
@IBOutlet var finishButton: GradientButton!
的接口,那么如何通过convenience init(leftColor: UIColor, rightColor: UIColor, image: UIImage)
设置其颜色? - Mamta
UIImageView
上面,或者使用setBackgroundImage(for:)
来指定一张图片 - 如果你想要在下面显示一些东西,也许可以加上线性渐变和透明度。 - MadProgrammer