我正在尝试将自定义MyButton
UIButton的背景颜色设置为按钮的当前背景颜色,其中包含突出显示状态的alpha分量。类似于当按钮处于突出显示状态时,UIButton的文本标题如何变暗/变暗。
我一直在努力实现这一目标,并且最终提出了这行似乎最有意义的代码,但是,它不起作用:
self.setBackgroundColor((self.backgroundColor?.colorWithAlphaComponent(0.5))!, forState: .Highlighted)
我感谢任何帮助。谢谢!
import UIKit
class MyButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 25.0
self.clipsToBounds = true
self.setBackgroundColor((self.backgroundColor?.colorWithAlphaComponent(0.5))!, forState: .Highlighted)
}
}
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, forState: forState)
}
}
更新