1

I wanted to add circle image on left navigation bar item as button. I could added, but it is not circle it is ellipse. Here is my code.

let button = UIButton();
button.downloaded(from: user?.Image);
button.frame = CGRect(x: 0, y: 0, width: 36, height:36);
button.layer.cornerRadius = button.frame.width / 2;
button.layer.masksToBounds = true;
button.imageView?.contentMode = .scaleAspectFill;
let barBtn = UIBarButtonItem(customView: button);
self.navigationItem.leftBarButtonItem = barBtn;

You can check my screen shot. Can you help me?

enter image description here

Volkan Sonmez
  • 745
  • 3
  • 14
  • If you are looking for Swift 5 solution, here is my answer: https://stackoverflow.com/a/58623149/7987502 – Egzon P. Oct 30 '19 at 10:35

1 Answers1

4

Issue arises when downloaded image is larger than (36, 36) it resets the frame of imageView and as result UIbutton's frame is also reset. You need to resize the image before assigning it to imageView making it smaller than (36,36).

Also don't make UIButton round, make imageView round. Otherwise touchable area of button will be reduced.

use:

button.imageView.layer.cornerRadius = button.imageView.frame.width / 2;
button.imageView.layer.masksToBounds = true;

Instead of:

button.layer.cornerRadius = button.frame.width / 2;
button.layer.masksToBounds = true;

Refer to following answer for resizing images.

How to Resize image in Swift?

  • My button works when i added my view as subviews. It does not work navigation bar. I tried your code with resizing image. it is not circle – Volkan Sonmez Feb 06 '19 at 21:13
  • Make sure button's contentInset is zero, and you need to recalculate corner radius after image download process is completed, on main thread. Thanks. – Shmeel Ahmad Feb 06 '19 at 21:22