swiftrightbarbuttonitemnavigationitemios13.3

In iOS11 trying to add a round image as navigationItem in a NavigationBar and it is not clipping its edges


Using iOS13.3, XCode11.3,

I try to place a round Image as rightBarButtonItem on my largeTitle NavigationBar.

The button is drawn, however it does not get clipped and there are ugly corners in white remaining.

enter image description here

Here is my code (see below):

As you can see, I added the clipsToBounds = true to it - but I do not see the edges being clipped. Why ???

if let image = image {
    self.profileImage.image = image
} else {
    self.profileImage.image = #imageLiteral(resourceName: "profile-placeholder-small")
}

let button = UIButton(type: .custom)
button.setImage(self.profileImage.image, for: .normal)
button.addTarget(self, action:#selector(self.callMethod), for: .touchDragInside)
button.frame = CGRect(x: 0, y: 0, width: 36, height: 36)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton

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

self.profileImage.contentMode = .scaleAspectFit
self.profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2
self.profileImage.layer.masksToBounds = false
self.profileImage.clipsToBounds = true

Solution

  • You are adding button in navigation bar and setting clipToBounds to profileImage give corner radius to button instead of image will solve your issue. Currently your button is of size 36x36