swift 圆角阴影视图

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 圆角阴影视图相关的知识,希望对你有一定的参考价值。

import UIKit
import Foundation

/// This RoundedShadowView is a UIView class that has rounded corner as well as shadow in it.
@IBDesignable class RoundShadowView: UIView {
    
    private var shadowLayer: CAShapeLayer!
    
    /// This is the color of shadow.
    @IBInspectable private var shadowColor: UIColor = .black
    
    ///This is shadow opacity.
    @IBInspectable private var shadowOpacity: Float = 0.2
    
    ///This is the shadow width of the view.
    @IBInspectable private var shadowWidth: CGFloat = 0.0
    
    ///This is the shadow height of the view.
    @IBInspectable private var shadowHeight: CGFloat = 1.0
    
    /// This value changes the shadow Radius.
    @IBInspectable private var shadowRadius: CGFloat = 3
    
    /// This value changes the corner Radius of the view.
    @IBInspectable private var cornerRadius: CGFloat = 25.0
    
    /// The color applied to the shadow layer, rather than the view's backgroundColor.
    @IBInspectable private var fillColor: UIColor = .white
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if shadowLayer == nil {
            shadowLayer = CAShapeLayer()
            
            shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
            shadowLayer.fillColor = fillColor.cgColor
            
            shadowLayer.shadowColor = shadowColor.cgColor
            shadowLayer.shadowPath = shadowLayer.path
            shadowLayer.shadowOffset = CGSize(width: shadowWidth, height: shadowHeight)
            shadowLayer.shadowOpacity = shadowOpacity
            shadowLayer.shadowRadius = shadowRadius
            
            layer.insertSublayer(shadowLayer, at: 0)
        }
    }
}

以上是关于swift 圆角阴影视图的主要内容,如果未能解决你的问题,请参考以下文章

Swift - 圆角半径和阴影问题

如何创建具有边距、圆角和阴影的 UITableView?

带有圆角和阴影的 Swift uiview 不起作用

Swift-UIStoryboard & Xib 实时设置控件圆角边框阴影

Swift-UIStoryboard & Xib 实时设置控件圆角边框阴影

ios 视图既显示阴影又有圆角实现