Reputation: 2457
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
}
}
Shadow layer not resizing when UIView frame changed, how to change equal to the frame size, this is my whole code of UIviewcontroller
Upvotes: 7
Views: 2747
Reputation: 2727
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()
}
Upvotes: 2
Reputation: 3494
You have many ways to do that:
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
}
Upvotes: 2
Reputation: 54716
The issue is that you only draw the shadow once when the viewcontroller is loaded to memory, in viewDidLoad()
. You need to call dropShadow
every time you redraw the view it is linked to.
You can achieve this by calling dropShadow
after changing the frame of shadow
.
@IBAction func btnActn(_ sender: Any) {
self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
self.shadow.dropShadow()
}
Upvotes: 0