【发布时间】:2014-08-29 22:54:58
【问题描述】:
我正在尝试创建一个带有圆角和阴影的按钮。无论我如何切换,按钮都不会正确显示。我试过masksToBounds = false 和masksToBounds = true,但要么圆角半径起作用,阴影不起作用,要么阴影起作用,圆角半径不剪裁按钮的角。
import UIKit
import QuartzCore
@IBDesignable
class Button : UIButton
{
@IBInspectable var masksToBounds: Bool = false {didSet{updateLayerProperties()}}
@IBInspectable var cornerRadius : CGFloat = 0 {didSet{updateLayerProperties()}}
@IBInspectable var borderWidth : CGFloat = 0 {didSet{updateLayerProperties()}}
@IBInspectable var borderColor : UIColor = UIColor.clearColor() {didSet{updateLayerProperties()}}
@IBInspectable var shadowColor : UIColor = UIColor.clearColor() {didSet{updateLayerProperties()}}
@IBInspectable var shadowOpacity: CGFloat = 0 {didSet{updateLayerProperties()}}
@IBInspectable var shadowRadius : CGFloat = 0 {didSet{updateLayerProperties()}}
@IBInspectable var shadowOffset : CGSize = CGSizeMake(0, 0) {didSet{updateLayerProperties()}}
override func drawRect(rect: CGRect)
{
updateLayerProperties()
}
func updateLayerProperties()
{
self.layer.masksToBounds = masksToBounds
self.layer.cornerRadius = cornerRadius
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor.CGColor
self.layer.shadowColor = shadowColor.CGColor
self.layer.shadowOpacity = CFloat(shadowOpacity)
self.layer.shadowRadius = shadowRadius
self.layer.shadowOffset = shadowOffset
}
}
【问题讨论】:
-
您需要将阴影和剪辑放在不同的图层上。在
drawRect中设置图层属性并不是一个好主意。最好把它们放在initWithCoder。 -
对于任何在这里搜索的人来说,就像经常遇到非常古老的问题一样,这里的最佳答案虽然通常是正确的现在有一些严重错误。 (我输入了一个更正的答案。)大多数人,尤其是我,盲目地从顶部 SO 答案复制和粘贴 - 如果它是一个非常旧的 QA,请小心! (现在是 2020 年 - 5 年后必须有人取代我的答案!)
-
如果您的按钮有图像,那么您需要添加角半径以及按钮的 imageView。这将是最简单的方法
标签: ios swift shadow xcode6 cornerradius