3
我想创建一个UIButton
子类,并从颜色选择和禁用状态的背景图像。该UIButton的将是带有圆角边缘self.layer.cornerRadius = self.frame.height/2
从不同状态的颜色的UIButton背景图像
class RoundedButton: UIButton {
public var shadowOffset: CGSize = CGSize(width:0, height:0) {
didSet{
self.layer.shadowOffset = shadowOffset
}
}
public var shadowRadius: CGFloat = 0.0 {
didSet{
self.layer.shadowRadius = shadowRadius
}
}
public var shadowOpacity: Float = 1.0 {
didSet{
self.layer.shadowOpacity = shadowOpacity
}
}
public var shadowColor: UIColor = UIColor.black {
didSet{
self.layer.shadowColor = shadowColor.cgColor
}
}
public var selectedBackgroundColor: UIColor = UIColor.black
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = self.frame.height/2
self.setBackgroundImage(getImageWithColor(color: selectedBackgroundColor, size: self.frame.size, cornerRadius: self.frame.height/2), for: .selected)
}
func getImageWithColor(color: UIColor, size: CGSize, cornerRadius: CGFloat?) -> UIImage? {
let rect = CGRect(x:0, y:0, width:size.width, height:size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
if cornerRadius != nil {
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius!).addClip()
}
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
当我选择按钮(我做更改状态时,该按钮被点击)的怪异认为该按钮只检测第一次在它不工作窃听。另一个奇怪的行为是,如果我分配一个正常的UIImage
(不是由核心图形创建的),它的工作原理可能会产生错误的图像。
请注意,我需要结合阴影,圆角半径和能够从UIColor具有不同的背景按钮状态颜色。