There are many answers to this question, but they all do not look very useful if you really want to use backgroundColor to style your buttons. UIButton has a good option to set different images for different control states, but there is no other function for background colors. Therefore, one solution is to add an extension that will generate images from the color and apply them to the button.
extension UIButton { private func image(withColor color: UIColor) -> UIImage? { let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func setBackgroundColor(_ color: UIColor, for state: UIControlState) { self.setBackgroundImage(image(withColor: color), for: state) } }
Only one problem with this solution is that this change will not be applied to buttons created in the storyboard. For me, this is not a problem, because I prefer to style the user interface from code. If you want to use storyboards, then you need extra magic with @IBInspectable .
The second option is to create subclasses, but I prefer to avoid this.
Dzmitry Navak Aug 15 '18 at 14:40 2018-08-15 14:40
source share