到目前为止,我一直在努力实现您可以在下图中看到的左栏按钮项目:
{{3}}
我还没有编写风格,只是获取个人资料图片的基本代码。这是:
let user = FIRAuth.auth()?.currentUser
var profilePicture: UIImageView?
override func viewDidLoad() {
//left bar button item setup
if let profileURL = self.user?.photoURL?.absoluteString {
let profilePictureUrl = NSURL(string: profileURL)
profilePicture?.af_setImage(withURL: profilePictureUrl as! URL)
let barButton = UIBarButtonItem(image: profilePicture?.image, landscapeImagePhone: nil, style: .done, target: self, action: #selector(revealBackClicked))
self.navigationItem.leftBarButtonItem = barButton
}
}
我正在使用以下功能从firebase检索我的照片:
self.user?.photoURL?.absoluteString
我收到了一个网址,因为我在输出中打印了它。但是,我认为问题是当我在profilePicture变量中设置图像时,因为当我打印出来时,我收到的是nil。
非常感谢任何帮助!
答案 0 :(得分:2)
在下载图像时,您尝试将图像设置为UIBarButtonItem的问题。您应下载图像,然后将图像设置为UIBarButtonItem。
let profilePictureUrl = NSURL(string: profileURL)
let downloader = ImageDownloader()
let urlRequest = URLRequest(url: profilePictureUrl)
downloader.download(urlRequest) { response in
if let image = response.result.value {
let barButton = UIBarButtonItem(image: image, landscapeImagePhone: nil, style: .done, target: self, action: #selector(revealBackClicked))
self.navigationItem.leftBarButtonItem = barButton
}
}
答案 1 :(得分:1)
let user = FIRAuth.auth()?.currentUser
override func viewDidLoad() {
super.viewDidLoad()
let profilePictureURL = self.user?.photoURL
DispatchQueue.global().async {
let data = try? Data(contentsOf: profilePictureURL!)
DispatchQueue.main.async {
let button = UIButton.init(type: .custom)
button.setImage(UIImage(data: data!), for: UIControlState.normal)
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.clipsToBounds = true
button.addTarget(self, action: #selector(UserGroupsMainViewController.profileButtonPressed), for: UIControlEvents.touchUpInside)
button.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItem = barButton
}
}
}
func profileButtonPressed() {
print("Show Profile")
}
答案 2 :(得分:0)
斯威夫特和核弹
<块引用>使用 Nuke 为 UIBarButtonItem 将图像插入按钮。
在 ImagePipeline 的帮助下,我们可以轻松获取图像并在任何我们想要的地方使用它。
guard let url = URL(string: "https://....") else { return }
ImagePipeline.shared.loadImage(with: url) { result in
switch result {
case .success(let data):
DispatchQueue.main.async {
let button = UIButton()
button.setImage(data.image, for: .normal)
button.layer.cornerRadius = button.bounds.size.height/2
button.clipsToBounds = true
button.addTarget(self, action: #selector(profileButtonPressed), for: UIControlEvents.touchUpInside)
button.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItem = barButton
}
break
case .failure:
break
}
}