当UIView帧改变时,阴影层不会调整大小

时间:2018-04-28 10:46:32

标签: ios swift uiview shadow

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

3 个答案:

答案 0 :(得分:0)

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

您可以在更改dropShadow

的框架后致电shadow来实现此目的
@IBAction func btnActn(_ sender: Any) {
    self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
    self.shadow.dropShadow()
}

答案 1 :(得分:0)

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

  

首先:在' viewWillLayoutSubviews'方法,你必须像这样调用你的阴影方法。因此,无论何时更改框架,您都不必担心图层。更改视图后,此方法将自动调用: -

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

第二:当您要重新构建视图大小时,您必须设置" true" for" autoresizesSubviews"像这样:

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

答案 2 :(得分:0)

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()
        }