使用swift 3在UIView上添加Shadow [英] add Shadow on UIView using swift 3
问题描述
之前的swift 3我在我的UIView中添加阴影,如下所示:
prior swift 3 i was adding shadow in my UIView like this :
//toolbar is an UIToolbar (UIView)
toolbar.layer.masksToBounds = false
toolbar.layer.shadowOffset = CGSize(width: -1, height: 1)
toolbar.layer.shadowRadius = 1
toolbar.layer.shadowOpacity = 0.5
但上面的代码在swift 3中不起作用,而不是影子我的整个View的颜色变成丑陋的灰色
but the above code is not working in swift 3 , instead of shadow my whole View's color is turned to ugly gray
任何人都知道如何在swift 3中添加阴影?
anyone knows how can we add shadow in swift 3 ?
推荐答案
CODE SNIPPET
extension UIView {
// OUTPUT 1
func dropShadow(scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: -1, height: 1)
layer.shadowRadius = 1
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
// OUTPUT 2
func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowOffset = offSet
layer.shadowRadius = radius
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
注意:如果未将任何参数传递给该函数,则默认情况下scale参数将为true。您可以通过在该参数的类型之后为参数赋值来为函数中的任何参数定义默认值。如果定义了默认值,则可以在调用函数时省略该参数。
NOTE: If you don't pass any parameter to that function, then the scale argument will be true by default. You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.
输出1:
shadowView.dropShadow()
输出2:
shadowView.dropShadow(color: .red, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true)
这篇关于使用swift 3在UIView上添加Shadow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!