Search code examples
iosswiftuibarbuttonitemsdwebimage

Bar button item not appearing with image


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


Solution

  • 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
        }
    }