首页 > 解决方案 > 如何将 css 盒子阴影转换为 IOS 阴影

问题描述

我想知道如何将以下 CSS 框阴影转换为 iOS 阴影。CSS框阴影如下

box-shadow: -2px -4px 4px 0 #e5e5e5, 2px 4px 4px 0 rgba(0, 0, 0, 0.25);

标签: cssiosswift

解决方案


如果这是你想要的:

在此处输入图像描述

您可以通过设置视图的layer阴影并添加带有另一个阴影的子层来做到这一点:

class BoxShadowView: UIView {
    
    let layer1 = CALayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        
        layer.masksToBounds = false
        layer.shouldRasterize = true
        layer.shadowRadius = 4
        layer.shadowOffset = CGSize(width: -2, height: -4)
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.1
        
        layer1.masksToBounds = false
        layer1.shouldRasterize = true
        layer1.shadowRadius = 4
        layer1.shadowOffset = CGSize(width: 2, height: 4)
        layer1.shadowColor = UIColor.black.cgColor
        layer1.shadowOpacity = 0.25
        
        layer.addSublayer(layer1)
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        layer1.backgroundColor = backgroundColor?.cgColor
        layer1.frame = bounds
    }
    
}

这是一个简单的示例用法(我用来创建该图像的内容):

class BoxShadowTestViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // create a BoxShadowView
        let boxView = BoxShadowView()
        
        // create a label
        let label = UILabel()
        
        [boxView, label].forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
        }
        
        // add label to boxView
        boxView.addSubview(label)
        
        // add boxView to view
        view.addSubview(boxView)
        
        // respect safe area
        let g = view.safeAreaLayoutGuide
        
        NSLayoutConstraint.activate([
            
            // boxView Width & Height
            boxView.widthAnchor.constraint(equalToConstant: 240.0),
            boxView.heightAnchor.constraint(equalToConstant: 120.0),
            // center in view
            boxView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            boxView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
            
            // center label in boxView
            label.centerXAnchor.constraint(equalTo: boxView.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: boxView.centerYAnchor),

        ])
        
        // set boxView background color
        boxView.backgroundColor = .white
        
        // set label text
        label.text = "Test Label"
        
    }
    
}

推荐阅读