UIView with rounded corners and drop shadow?

前端 未结 30 3161
一整个雨季
一整个雨季 2020-11-22 08:00

I’ve been working on an application for a couple of years and received a simple design request: Round the corners on a UIView and add a drop shadow.To do as given below.

30条回答
  •  清歌不尽
    2020-11-22 08:26

    Check out the example project on GitHub to make sure you use the component correctly.

    Simple Swift 5 solution without any additional subviews or subclassing:

    extension UIView {
    
        func addShadow(offset: CGSize, color: UIColor, radius: CGFloat, opacity: Float) {
            layer.masksToBounds = false
            layer.shadowOffset = offset
            layer.shadowColor = color.cgColor
            layer.shadowRadius = radius
            layer.shadowOpacity = opacity
    
            let backgroundCGColor = backgroundColor?.cgColor
            backgroundColor = nil
            layer.backgroundColor =  backgroundCGColor
        }
    }
    

    Note that you should set up your view with corner radius and other properties before calling addShadow.

    After that, just call this from viewDidLoad like this:

    button.addShadow(offset: CGSize.init(width: 0, height: 3), color: UIColor.black, radius: 2.0, opacity: 0.35)
    

    Final result:

    Super easy and simple!

提交回复
热议问题