ios - 来自不同状态的颜色的 UIButton 背景图像

标签 ios swift uibutton uikit core-graphics

我正在尝试创建一个 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 的不同背景按钮状态颜色。

最佳答案

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

或者,您可以观察 isSelectedisHighlighted 等,然后简单地设置按钮的 backgroundColor 属性。

关于ios - 来自不同状态的颜色的 UIButton 背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45833988/

相关文章:

swift - SpriteKit "START"在场景中调用 start() 的按钮

ios - UITableViewCell 不响应响应者链

ios - 如何使用户无需在 URL 前键入 "http://"?

iphone - UITableViewCell 中 UILabel 文本的位置

ios - Realm 中列表的默认值

swift - SecIdentity + Force Cast 违规 : Force casts should be avoided. (force_cast)

ios - 检测何时无法正确显示 unicode 字符

ios - Xcode "Device Locked"iPhone 解锁时

ios - 将图像传递到另一个 View Controller (Swift)

ios - 快速获取 UIButton 内标题标签的框架