Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shadow on custom navigation bar button item clipping to bounds

I have a back button item on my navigation bar that I want to use include a drop shadow on but the drop shadow clips to the navbar bounds. Is it possible shadows extend past the bounds of the navbar?

I've simplified and greatly exaggerated the effect in this example: enter image description here

The code for the button looks something like this:

    let button = UIButton();
    button.layer.shadowOffset = CGSize(width: 0, height: 12);
    button.layer.shadowColor = UIColor(red: 0.06, green: 0.09, blue: 0.13, alpha: 0.8).cgColor;
    button.layer.shadowOpacity = 1;
    button.layer.shadowRadius = 14;
    button.backgroundColor = UIColor(red:0, green:0.65, blue:0.57, alpha:1);
    button.layer.cornerRadius = 20;

    button.translatesAutoresizingMaskIntoConstraints = false;
    button.widthAnchor.constraint(equalToConstant: 40).isActive = true;
    button.heightAnchor.constraint(equalToConstant: 40).isActive = true;

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button);

I also set my navigation bar to transparent with the following code:

    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default);
    self.navigationController?.navigationBar.shadowImage = UIImage();
    self.navigationController?.navigationBar.isTranslucent = true;

I've already tried a setting clipsToBounds and layer.masksToBounds to false on the navigationBar but that doesn't fix the issue. I figure as a hack I could probably just increase the size of the navigationBar and reposition the button so the shadow doesn't clip the statusBar but hoping someone knows a more ideal solution.

like image 260
Jacob Lange Avatar asked Oct 27 '25 03:10

Jacob Lange


1 Answers

Although I don't think this is good idea to add such a shadow in a navigation bar, but if you want, add the following code in you view controller, it should work.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.navigationController?.navigationBar.subviews.forEach {
        $0.clipsToBounds = false
    }
}
like image 122
JIE WANG Avatar answered Oct 28 '25 17:10

JIE WANG