这似乎是一个棘手的问题,我无法找到解决方案。
我需要带有以下内容的UIButton
:
对于状态子类化为UIButton
并设置参数,我可以获得拐角半径和背景色:
// The button is set to "type: Custom" in the interface builder.
// 1. rounded corners
self.layer.cornerRadius = 10.0
// 2. Color for state
self.backgroundColor = UIColor.orange // for state .normal
self.setBackgroundColor(color: UIColor.red, forState: .highlighted)
// 3. Add the shadow
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 3)
self.layer.shadowOpacity = 0.3
self.layer.shadowRadius = 6.0
self.layer.masksToBounds = false
// I'm also using an extension to be able to set the background color
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControl.State) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
}
}
问题:呈现按钮后,看起来很好,具有所需的背景颜色,圆角和阴影。但是一旦按下setBackgroundImage(image, for: forState)
就会启动并摆脱半径,因此按钮[[显示为正方形具有所需的颜色和阴影。
.highlighted
)是否有保留半径的方法?例如,我确实尝试过this post的解决方案,但没有人考虑setBackgroundImage(image, for: forState)
。我找不到任何有效的方法...
.normal
和.highlighted
的背景颜色-也就是说,您没有需要背景图像-您可以覆盖var isHighlighted
来处理颜色更改。
UIButton
子类。它标记为@IBDesignable
,并具有标记为normalBackground
的highlightBackground
和@IBInspectable
颜色,因此您可以在Storyboard / Interface Builder中对其进行设置:@IBDesignable
class HighlightButton: UIButton {
@IBInspectable
var normalBackground: UIColor = .clear {
didSet {
backgroundColor = self.normalBackground
}
}
@IBInspectable
var highlightBackground: UIColor = .clear
override open var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? highlightBackground : normalBackground
}
}
func setBackgroundColor(_ c: UIColor, forState: UIControl.State) -> Void {
if forState == UIControl.State.normal {
normalBackground = c
} else if forState == UIControl.State.highlighted {
highlightBackground = c
} else {
// implement other states as desired
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
// 1. rounded corners
self.layer.cornerRadius = 10.0
// 2. Default Colors for state
self.setBackgroundColor(.orange, forState: .normal)
self.setBackgroundColor(.red, forState: .highlighted)
// 3. Add the shadow
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 3)
self.layer.shadowOpacity = 0.3
self.layer.shadowRadius = 6.0
self.layer.masksToBounds = false
}
}