【发布时间】:2020-06-10 19:40:10
【问题描述】:
这似乎是一个棘手的问题,我找不到解决方案。
我需要一个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)。我找不到任何有用的东西...
【问题讨论】:
-
您是否打算为您的按钮设置一个实际的背景图像?或者你只是因为没有默认的 backgroundColor for state 属性而这样做?
-
正如你所说,你的回答完全符合我的需要。