ios 使用 swift 3 在 UIView 上添加阴影

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39624675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:18:13  来源:igfitidea点击:

add Shadow on UIView using swift 3

iosswift3

提问by remy boys

prior swift 3 i was adding shadow in my UIView like this :

在 swift 3 之前,我在 UIView 中添加阴影,如下所示:

//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

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 ?

有谁知道我们如何在 swift 3 中添加阴影?

回答by aashish tamsya

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
  }
}

NOTE: If you don't pass anyparameter 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.

注意:如果您不向该函数传递任何参数,则默认情况下 scale 参数将为 true。您可以为函数中的任何参数定义默认值,方法是在该参数的类型之后为该参数分配一个值。如果定义了默认值,则可以在调用函数时省略该参数。

OUTPUT 1:

输出 1:

shadowView.dropShadow()

enter image description here

在此处输入图片说明

OUTPUT 2:

输出 2:

shadowView.dropShadow(color: .red, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true)

enter image description here

在此处输入图片说明

layer.shouldRasterize = truewill make the shadow static and cause a shadow for the initial state of the UIView. So I would recommend not to use layer.shouldRasterize = truein dynamic layouts like view inside a UITableViewCell.

layer.shouldRasterize = true将使阴影静止并为 的初始状态产生阴影UIView。所以我建议不要layer.shouldRasterize = true在动态布局中使用,比如在UITableViewCell.

回答by Vinu David Jose

Shadow using UIView Extension Swift 4

使用 UIView 扩展 Swift 4 的阴影

I would like to add one more line with selected answer! When we rasterizing the layer, It needs to be set to 2.0 for retina displays. Otherwise label text or images on that view will be blurry. So we need to add rasterizationScalealso.

我想再添加一行并选择答案!当我们光栅化图层时,它需要设置为 2.0 以用于视网膜显示。否则该视图上的标签文本或图像将变得模糊。所以我们还需要添加rasterizationScale

  extension UIView {

    func dropShadow() {
        self.layer.masksToBounds = false
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOpacity = 0.5
        self.layer.shadowOffset = CGSize(width: -1, height: 1)
        self.layer.shadowRadius = 1
        self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = UIScreen.main.scale

    }
}

回答by Mr.Javed Multani

Very simple and few lines of code:

非常简单,几行代码:

let viewShadow = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
viewShadow.center = self.view.center
viewShadow.backgroundColor = UIColor.yellow
viewShadow.layer.shadowColor = UIColor.red.cgColor
viewShadow.layer.shadowOpacity = 1
viewShadow.layer.shadowOffset = CGSize.zero
viewShadow.layer.shadowRadius = 5
self.view.addSubview(viewShadow)

Look like : enter image description here

看起来像 : 在此处输入图片说明

回答by Chhaileng

This works for me (Swift 3 and 4)

这对我有用(Swift 3 和 4)

yourView.layer.shadowColor = UIColor.gray.cgColor
yourView.layer.shadowOpacity = 0.3
yourView.layer.shadowOffset = CGSize.zero
yourView.layer.shadowRadius = 6

回答by Mihai HG

Very easy to use extension for UIView, editable directly from storyboard. Swift 4+

非常易于使用的 UIView 扩展,可直接从故事板编辑。斯威夫特 4+

@IBDesignable extension UIView {
    @IBInspectable var shadowColor: UIColor?{
        set {
            guard let uiColor = newValue else { return }
            layer.shadowColor = uiColor.cgColor
        }
        get{
            guard let color = layer.shadowColor else { return nil }
            return UIColor(cgColor: color)
        }
    }

    @IBInspectable var shadowOpacity: Float{
        set {
            layer.shadowOpacity = newValue
        }
        get{
            return layer.shadowOpacity
        }
    }

    @IBInspectable var shadowOffset: CGSize{
        set {
            layer.shadowOffset = newValue
        }
        get{
            return layer.shadowOffset
        }
    }

    @IBInspectable var shadowRadius: CGFloat{
        set {
            layer.shadowRadius = newValue
        }
        get{
            return layer.shadowRadius
        }
    }
}

回答by budidino

Although the accepted answeris great and it works as it should, I've modified it to split offSet: CGSizeto offsetX: CGFloatand offsetY: CGFloat.

尽管接受的答案很好并且可以正常工作,但我已将其修改为拆分offSet: CGSizeoffsetX: CGFloatoffsetY: CGFloat

extension UIView {
  func dropShadow(offsetX: CGFloat, offsetY: CGFloat, color: UIColor, opacity: Float, radius: CGFloat, scale: Bool = true) {
    layer.masksToBounds = false
    layer.shadowOffset = CGSize(width: offsetX, height: offsetY)
    layer.shadowColor = color.cgColor
    layer.shadowOpacity = opacity
    layer.shadowRadius = radius
    layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
    layer.shouldRasterize = true
    layer.rasterizationScale = scale ? UIScreen.main.scale : 1
  }
}

回答by Anton Sokolov

If you need rounded shadow. Works for swift 4.2

如果您需要圆形阴影。适用于 swift 4.2

extension UIView {

        func dropShadow() {

            var shadowLayer: CAShapeLayer!
            let cornerRadius: CGFloat = 16.0
            let fillColor: UIColor = .white

            if shadowLayer == nil {
                shadowLayer = CAShapeLayer()

                shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
                shadowLayer.fillColor = fillColor.cgColor

                shadowLayer.shadowColor = UIColor.black.cgColor
                shadowLayer.shadowPath = shadowLayer.path
                shadowLayer.shadowOffset = CGSize(width: -2.0, height: 2.0)
                shadowLayer.shadowOpacity = 0.8
                shadowLayer.shadowRadius = 2

                layer.insertSublayer(shadowLayer, at: 0)
            }
        }
    }

Swift 4 rounded UIView with shadow

Swift 4 带阴影的圆形 UIView

回答by Hariom tyagi

Please Try this

请试试这个

func applyShadowOnView(_ view: UIView) {
    view.layer.cornerRadius = 8
    view.layer.shadowColor = UIColor.darkGray.cgColor
    view.layer.shadowOpacity = 1
    view.layer.shadowOffset = .zero
    view.layer.shadowRadius = 5
}

回答by Merry

Please try this, it's working for me.

请试试这个,它对我有用。

extension UIView {


func dropShadow() {

    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOffset = CGSize(width: 2, height: 3)
    layer.masksToBounds = false

    layer.shadowOpacity = 0.3
    layer.shadowRadius = 3
    //layer.shadowPath = UIBezierPath(rect: bounds).cgPath
    layer.rasterizationScale = UIScreen.main.scale
    layer.shouldRasterize = true
}}

回答by Shakeel Ahmed

Swift 5 Just call this function and pass your view

Swift 5 只需调用此函数并传递您的视图

public func setViewSettingWithBgShade(view: UIView)
{
    view.layer.cornerRadius = 8
    view.layer.borderWidth = 1
    view.layer.borderColor = AppTextFieldBorderColor.cgColor

    //MARK:- Shade a view
    view.layer.shadowOpacity = 0.5
    view.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
    view.layer.shadowRadius = 3.0
    view.layer.shadowColor = UIColor.black.cgColor
    view.layer.masksToBounds = false
}