UIView 框架改变时阴影层不调整大小

Shadow layer not resizing when UIView frame changed

Issue Image ScreenShot

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 frame改变时阴影层没有调整大小,如何改变等于frame size,这是我的UIviewcontroller的全部代码

问题是当 viewcontroller 加载到内存时,您只在 viewDidLoad() 中绘制一次阴影。每次重绘链接到的视图时都需要调用 dropShadow

您可以通过在更改 shadow 的框架后调用 dropShadow 来实现。

@IBAction func btnActn(_ sender: Any) {
    self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
    self.shadow.dropShadow()
}

你有很多方法可以做到这一点:

First: In 'viewWillLayoutSubviews' method, you have to call your shadow method like this. so whenever you changed the frame then you have not worry about layers. This method will auto call whenever you have changed the view:-

override func viewWillLayoutSubviews() {
    shadow.dropShadow()
}

Second: When you are going to re-frame you view size then you have to set "true" for "autoresizesSubviews" like this:

@IBAction func btnActn(_ sender: Any) {
        self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
        self.shadow.autoresizesSubviews = true
    }
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()
        }