Californium
Californium

Reputation: 591

Constraints affecting shadow of UIView?

I am trying to establish a shadow on all four sides of my UIView in my ViewController — which works perfectly fine until I add constraints to the UIView via Xcode. How can I make the shadow of the UIView display on all four sides with set constraints for all sides?

Essentially, what I've discovered is that whenever I apply constraints via Xcode to the UIView that I have set the shadow around, the shadow does not appear under all four sides of the UIView. Instead, it floats to the left, leaving the right and bottom sides completely without shadowing. This can be seen in the screenshots beneath.

https://i.sstatic.net/BNvaW.jpg

class RegistrationViewController: UIViewController {
    @IBOutlet weak var signUpView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        signUpView.clipsToBounds = true
        signUpView.layer.cornerRadius = 20;
        signUpView.layer.shadowPath = UIBezierPath(roundedRect: signUpView.bounds, cornerRadius: signUpView.layer.cornerRadius).cgPath
        signUpView.layer.shouldRasterize = true
        signUpView.layer.shadowColor = UIColor.black.cgColor
        signUpView.layer.shadowOffset = .zero
        signUpView.layer.shadowOpacity = 1
        signUpView.layer.shadowRadius = 20
        signUpView.layer.masksToBounds = false

    // Do any additional setup after loading the view.
    }
}

Why is this happening and how can I add constraints while keeping the desired result?

Upvotes: 0

Views: 1188

Answers (1)

Mocha
Mocha

Reputation: 2253

In viewDidLoad, your constraints have not taken affect yet. So when you create your UIBezierPath, the bounds are not updated to the auto-layout constraints. The bounds that are used are probably the ones in your .xib file.

Move your shadowMakingPath into viewDidLayoutSubviews

override func viewDidLayoutSubviews() {
   super.viewDidLayoutSubivews()
   signUpView.layer.shadowPath = UIBezierPath(roundedRect: signUpView.bounds, cornerRadius: signUpView.layer.cornerRadius).cgPath
   signUpView.layer.shouldRasterize = true
   signUpView.layer.shadowColor = UIColor.black.cgColor
   signUpView.layer.shadowOffset = .zero
   signUpView.layer.shadowOpacity = 1
   signUpView.layer.shadowRadius = 20
   signUpView.layer.masksToBounds = false
}

More information .. Objective-C/Swift (iOS) When are the auto-constraints applied in the View/ViewController work flow?

Upvotes: 2

Related Questions