class ViewController: UIViewController {
var shadow : UIView!
override func viewDidLoad() {
super.viewDidLoad()
shadow = UIView(frame: CGRect(x: 50,y: 50,width: 150,height:150))
shadow.backgroundColor = .red
shadow.dropShadow()
self.view.addSubview(shadow)
}
@IBAction func btnActn(_ sender: Any) {self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
}
}
extension UIView {
func dropShadow(scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: 1, height: 1)
layer.shadowRadius = 2
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
当UIView帧改变时,阴影层不调整大小,如何更改等于帧大小,这是我的整个UIviewcontroller代码。
发布于 2018-04-28 03:26:27
你有很多方法可以做到这一点:
First:在'viewWillLayoutSubviews‘方法中,您必须像这样调用影子方法。所以,每当你改变了框架,你就不用担心层次了。当您更改视图时,此方法将自动调用:
override func viewWillLayoutSubviews() {
shadow.dropShadow()
}
第二步:当要重新帧时,您必须查看大小,然后必须为"autoresizesSubviews“设置"true”,如下所示:
@IBAction func btnActn(_ sender: Any) {
self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
self.shadow.autoresizesSubviews = true
}
发布于 2018-04-28 09:55:58
Before calling dropShadow, first, try to call layoutIfNeeded
@IBAction func btnActn(_ sender: Any) {
self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
self.shadow.layoutIfNeeded()
self.shadow.dropShadow()
}
发布于 2018-04-28 03:06:25
问题是,当视图控制器加载到内存中时(在viewDidLoad()
中),您只绘制一次阴影。每次重新绘制链接到的视图时,都需要调用dropShadow
。
您可以通过在更改dropShadow
的框架后调用shadow
来实现这一点。
@IBAction func btnActn(_ sender: Any) {
self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
self.shadow.dropShadow()
}
https://stackoverflow.com/questions/50075673
复制