Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/116.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios UIButton来自不同状态的彩色背景图像_Ios_Swift_Uibutton_Uikit_Core Graphics - Fatal编程技术网

Ios UIButton来自不同状态的彩色背景图像

Ios UIButton来自不同状态的彩色背景图像,ios,swift,uibutton,uikit,core-graphics,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

我试图创建一个
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
函数中设置图像。只需覆盖初始值设定项并为所有状态设置背景图像即可

或者,您可以观察
isSelected
isHighlighted
等,只需设置按钮的
backgroundColor
属性