我创建了一个左侧导航栏按钮,但我不知道如何将图像从网址存储到按钮图像中。下面是我的导航栏左键代码
navigationItem.leftBarButtonItem = UIBarButtonItem(image: <#T##UIImage?#>, style: .plain, target: self, action: #selector(handleButtonPressed))
我应该创建UIimage变量然后将其用于图像参数吗?有什么建议?谢谢!
答案 0 :(得分:0)
您需要先下载图像。因此,对于下载时间,您可以设置占位符图像,也可以根本不显示占位符图像。但是这段代码可以帮到你。
fund viewDidLoad() {
super.viewDidLoad()
let placeholderImage = UIImage(named: "placeholder")
updateLeftNavigationItem(with: placeholderImage)
loadNavigationBarImage(from: URL(string: "<your url>")!)
}
func updateLeftNavigationItem(with image: UIImage?) {
navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(handleButtonPressed))
}
func loadNavigationBarImage(from url: URL) {
getDataFromUrl(url: url) { data, response, error in
guard let data = data, error == nil else { return }
DispatchQueue.main.async() { [weak self] in
let image = UIImage(data: data)
self?.updateLeftNavigationItem(with: image)
}
}
}
func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url) { data, response, error in
completion(data, response, error)
}.resume()
}
初始状态
答案 1 :(得分:0)
您可以将图片从网址设置为条形按钮,如下所示: 首先将url转换为数据,然后转换为UIImage,然后使用它
let url = URL(string:"http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
if let data = try? Data(contentsOf: url!)
{
let Serverimage: UIImage = UIImage(data: data)
let barButton = UIBarButtonItem(image: Serverimage, landscapeImagePhone: nil, style: .Done, target: self, action: #selector(handleButtonPressed))
self.navigationItem.leftBarButtonItem = barButton
}
一切顺利。希望这会对你有所帮助。