简体   繁体   中英

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.

在此处输入图像描述 在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM