gpt4 book ai didi

ios - 图像未显示在 BarButtonItem 中

转载 作者:可可西里 更新时间:2023-11-01 01:07:56 24 4
gpt4 key购买 nike

我想在我的栏按钮项目图像中显示当前用户的个人资料图片。将显示默认图片,但不会显示用户的个人资料图片。

条形按钮图片声明:

lazy var leftButton: UIBarButtonItem = {
var image = UIImage.init(named: "icons8-kontakte-50")?.withRenderingMode(.alwaysOriginal)
let button = UIBarButtonItem.init(image: image, style: .plain, target: self, action: #selector(ConversationViewController.showProfile))
return button
}()

这里我观察当前用户,获取当前头像:

 //left bar button image fetching
self.navigationItem.leftBarButtonItem = self.leftButton
self.tableView.tableFooterView = UIView.init(frame: CGRect.zero)

UserApi.shared.observeCurrentUser { (currentUser) in
self.currentUser = currentUser

guard let url = URL(string: currentUser.profilImageUrl!) else { return }

URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error == nil {
let image = UIImage.init(data: data!)

let contentSize = CGSize.init(width: 30, height: 30)
UIGraphicsBeginImageContextWithOptions(contentSize, false, 0.0)
let _ = UIBezierPath.init(roundedRect: CGRect.init(origin: CGPoint.zero, size: contentSize), cornerRadius: 14).addClip()
image!.draw(in: CGRect(origin: CGPoint.zero, size: contentSize))
let path = UIBezierPath.init(roundedRect: CGRect.init(origin: CGPoint.zero, size: contentSize), cornerRadius: 14)
path.lineWidth = 2
UIColor.white.setStroke()
path.stroke()
let finalImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!.withRenderingMode(.alwaysOriginal)
UIGraphicsEndImageContext()
self.leftButton.image = finalImage

}
})

预先感谢您的帮助!

最佳答案

数据任务完成 block 可以在任何线程上调用,但 UI 更新必须在主线程上完成。您需要分派(dispatch)回主线程以更新您的 UIBarButtonItem

URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil, let data = data, let image = UIImage(data: data) else { return }
let size = CGSize(width: 30, height: 30)
let rect = CGRect(origin: .zero, size: size)
let finalImage = UIGraphicsImageRenderer(size: size).image { _ in
let path = UIBezierPath(ovalIn: rect)
path.addClip()
image.draw(in: CGRect(origin: CGPoint.zero, size: size))
path.lineWidth = 2.0
UIColor.white.setStroke()
path.stroke()
}
DispatchQueue.main.async {
self.leftButton.image = finalImage.withRenderMode(.alwaysOriginal)
}
}.resume()

您还需要对数据任务调用 resume()

关于ios - 图像未显示在 BarButtonItem 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53658687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com