【问题标题】:UIButton background image from color for different statesUIButton背景图像来自不同状态的颜色
【发布时间】:2017-08-23 08:02:18
【问题描述】:

我正在尝试创建一个UIButton 子类,并从颜色中选择和禁用状态背景图像。 UIButton 将带有圆角边缘self.layer.cornerRadius = self.frame.height/2

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 中获得不同的背景按钮状态颜色。

【问题讨论】:

    标签: ios swift uibutton uikit core-graphics


    【解决方案1】:

    您没有为其他状态设置背景图像:.normal, .disabled 在您的情况下。您也不需要在layoutSubviews 函数中设置图像。只需覆盖初始化程序并为那里的所有状态设置背景图像。

    您可以观察isSelectedisHighlighted 等并简单地设置按钮的backgroundColor 属性。

    【讨论】: