前言:
UI控件要寫陰影返干。這里陰影,它可能出現(xiàn)在各種UI控件上南蹂。
失敗的案例場(chǎng)景就不回放了犬金,因?yàn)闆]那個(gè)心情去寫了。
解決如下問題:
1六剥、寫陰影的時(shí)候晚顷,無需額外傳 UIBezierPath(roundedRect:這里面的bounds參數(shù)
2、在使用Xcode檢查的時(shí)候疗疟,不會(huì)出現(xiàn)陰影待優(yōu)化這樣的警告该默。
大神指引:
https://stackoverflow.com/questions/37645408/uitableviewcell-rounded-corners-and-shadow
效果圖:
寫陰影.png
代碼地址:
代碼地址:https://gitee.com/yuency/Autolayout
示例代碼類名 【W(wǎng)rightShadowController】
上代碼!
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")
}
}
結(jié)語
我以為之前的在 override func layoutSubviews() { } 這個(gè)函數(shù)里去拿到bounds策彤,然后添加陰影的方案是最好的了栓袖,然而還是在某天,cell里出現(xiàn)了陰影的bug店诗。layoutSubviews 會(huì)被多次調(diào)用裹刮,你還需要做一下處理,避免某些代碼不必要地多跑幾次∨尤常現(xiàn)在好了捧弃。我覺得根治了。