0

I am trying to set a profile picture as a bar button item. The picture comes from a URL using SDWebImage. When I run the app the item shows as a white box and all the other right bar button items shift left. Does anybody know what I'm doing wrong? Or if there's a better way to do this?

    @IBOutlet weak var myAvatarButton: UIBarButtonItem! {
    didSet {
        // call in "my user"
        guard let userImageURL = CurrentUser.shared.imageURL else {
            return
        }
        let avatarImage = UIImageView()
        avatarImage.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        avatarImage.sd_setImage(with: userImageURL, placeholderImage: #imageLiteral(resourceName: "placeholder"), options: [.refreshCached, .retryFailed], completed: nil)
        myAvatarButton.image = avatarImage.image
    }
}

The first photo is as shown in the simulator, and the second photo is from the storyboard.

enter image description here enter image description here

David
  • 155
  • 1
  • 10

1 Answers1

0

Use completion block. You are direct set image to button image but it takes time to download the image.

avatarImage.sd_setImage(with: userImageURL, placeholderImage: #imageLiteral(resourceName: "placeholder"), options: [.refreshCached, .retryFailed]) { (image, error, type, url) in
    if let image = image {
        myAvatarButton.image = image
    }
}
Raja Kishan
  • 16,767
  • 2
  • 26
  • 52
  • Thanks! The completion block and adding .withRenderingMode(UIImage.RenderingMode.alwaysOriginal) on that last line fixed this – David Mar 01 '21 at 06:12