3
votes

I am trying to create a UIButton subclass and have the selected and disabled state background image from color. The UIButton will be with rounded edges 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
}

}

It does not work when I select the button (I do change the state when the button is tapped) the weird think is that the button detect only the first time is being tapped. Another weird behaviour is that If I assign a normal UIImage (not created by core graphics) it works so maybe something wrong with the images generated.

Note that I need to combine shadow, corner radius and being able to have different background button states color from UIColor.

1

1 Answers

1
votes

You didn't set background image for other states: .normal, .disabled in your case. You also do not need to set the image in layoutSubviews function. Simply override the initializer and set background images for all states there.

Alternative you can observe isSelected, isHighlighted etc. and simply set the backgroundColor property of your button.