美文网首页
iOS Swift 写阴影最佳方案

iOS Swift 写阴影最佳方案

作者: Yuency | 来源:发表于2023-03-26 14:12 被阅读0次

前言:

UI控件要写阴影。这里阴影,它可能出现在各种UI控件上。
失败的案例场景就不回放了,因为没那个心情去写了。

解决如下问题:
1、写阴影的时候,无需额外传 UIBezierPath(roundedRect:这里面的bounds参数
2、在使用Xcode检查的时候,不会出现阴影待优化这样的警告。

大神指引:
https://stackoverflow.com/questions/37645408/uitableviewcell-rounded-corners-and-shadow

效果图:


写阴影.png

代码地址:

代码地址:https://gitee.com/yuency/Autolayout
示例代码类名 【WrightShadowController】

上代码!

WrightShadowController.swift

import UIKit

class WrightShadowController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let wrightShadowView = WrightShadowView()
        view.addSubview(wrightShadowView)
        wrightShadowView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.height.width.equalTo(200)
        }
    }
}

class WrightShadowView: UIView {
    
    override var bounds: CGRect {
        didSet {
            let cornerRadius: CGFloat = 20
            backgroundColor = UIColor.white
            layer.cornerRadius = cornerRadius
            layer.borderWidth = 0
            layer.borderColor = UIColor.white.cgColor
            layer.shadowColor = UIColor.black.cgColor
            layer.shadowOffset = CGSize(width: 0, height: 0)
            layer.shadowOpacity = 0.8
            layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

结语

我以为之前的在 override func layoutSubviews() { } 这个函数里去拿到bounds,然后添加阴影的方案是最好的了,然而还是在某天,cell里出现了阴影的bug。layoutSubviews 会被多次调用,你还需要做一下处理,避免某些代码不必要地多跑几次。现在好了。我觉得根治了。

相关文章

网友评论

      本文标题:iOS Swift 写阴影最佳方案

      本文链接:https://www.haomeiwen.com/subject/nkiordtx.html