0

How to set UIBarButton with circular image profile

ar

func loadProfile(){

        let url = URL(string: "https://res.cloudinary.com/demo/image/upload/v1312461204/sample.jpg")!

let data = try! Data(contentsOf: url)
let img = UIImage(data: data)
let imageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0))
imageView.image = img?.withRenderingMode(.alwaysOriginal)
imageView.layer.cornerRadius = 20.0
imageView.layer.masksToBounds = true
let barButton = UIBarButtonItem(customView: imageView)
self.tabBarController?.navigationItem.setRightBarButton(barButton, animated: false)
kiran
  • 4,285
  • 7
  • 53
  • 98

3 Answers3

1

Failed to set Constrains thats why its behaviors!

    imageView.widthAnchor.constraint(equalToConstant: buttonWidth).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true

Fixed Issue.

kiran
  • 4,285
  • 7
  • 53
  • 98
0

Have you tried set content mode in your imageView ?

imageView.contentMode = .scaleAspectFill
King.lbt
  • 843
  • 5
  • 15
0

For anyone that finds this, as suggested by kiran, setting the imageView frame size is not enough. You should also set the height and width constraints. Otherwise, any animation to the navigation bar will result in the imageView.image occupying the whole navigationBar width, as seen in the image posted by the OP.

func loadProfile(){
    let url = URL(string: "https://res.cloudinary.com/demo/image/upload/v1312461204/sample.jpg")!

    let data = try! Data(contentsOf: url)
    let img = UIImage(data: data)
    let imageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0))
    
    // NEW CODE HERE: Setting the constraints
    imageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
    
    imageView.image = img?.withRenderingMode(.alwaysOriginal)
    imageView.layer.cornerRadius = 20.0
    imageView.layer.masksToBounds = true
    let barButton = UIBarButtonItem(customView: imageView)
    self.tabBarController?.navigationItem.setRightBarButton(barButton, animated: false)
}