iosswiftuibuttonuibarbuttonitemuinavigationitem

Circular UIBarButtonItem button image get stretched


Added circular button on self.navigationItem.leftBarButtonItem for specific UIViewController of a TabBarcontroller after switching one tab and getting back to specific tab. The circular button is stretched.

override func viewDidLoad() {
    infoButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
    infoButton.sd_setBackgroundImage(with: URL(string: "https://www.w3schools.com/howto/img_avatar.png"), for: .normal)
    infoButton.addTarget(self, action: #selector(menuButtonPressed), for: .touchUpInside)
    infoButton.layer.cornerRadius = infoButton.bounds.size.width / 2
    infoButton.clipsToBounds = true
    infoButton.layer.borderWidth = 1.0
    infoButton.imageView?.contentMode = .scaleToFill
    infoButton.layer.borderColor = UIColor.init(hexString: "#AAC8FF").cgColor
    let infoItem = UIBarButtonItem(customView: infoButton)
    self.navigationItem.leftBarButtonItem = infoItem
}

Error Image: enter image description here


Solution

  • You forgot to give infoButton a size. You have to use auto layout. Give it a width constraint with a constant 40 and a height constraint with a constant 40.