我很困惑如何获取 DownloadURL(一个链接)并将其转换为图像并将其添加到我的表格视图单元格中?我的故事板中有一个图像视图,也不知道如何将其连接到表格视图单元格。谢谢!
override func viewDidLoad() { super.viewDidLoad()
let ref = FIRDatabase.database().reference().child("Posts")
ref.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot.childrenCount)
for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {
guard let value = rest.value as? Dictionary<String,Any> else { continue }
guard let downloadURL = value["DownloadURL"] as? String else { continue }
let post = postStruct(title: title, date: date, author: author, article: article, downloadURL: downloadURL)
self.posts.append(post)
}
self.posts = self.posts.reversed(); self.tableView.reloadData()
})
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let label1 = cell?.viewWithTag(1) as! UILabel
label1.text = posts[indexPath.row].title
return cell!
}
谷歌这个cocoapod:SDWebImage
用这个,太不可思议了
斯威夫特:
import SDWebImage
imageView.sd_setImage(with: URL(string: "url"), placeholderImage: UIImage(named: "placeholder.png"))
关于连接图像视图的第二个问题,您需要创建一个自定义单元格
1)您需要使用图像创建自定义单元类,如下所示:
class MyCustomCell: UITableViewCell {
//...some vars?
@IBOutlet myImageView: UIImageView!
//...some vars?
}
2)为您设置
table view
。你可以在google等找到很多关于点1和2的教程。示例:为tableView添加自定义单元格
3) 安装
KingFisher
用于缓存图像。 翠鸟。它将使您的桌面视图平滑滚动。 (注意:您可以使用任何类似物,例如 SDWebImage
)
安装:
1)
在你的 pod 文件中pod 'Kingfisher', '~> 3.0'
2)
在终端pod install
3)
在您的 swift 代码文件中import Kingfisher
4)在你的
table view
中使用它:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as! MyCustomCell
let row = indexPath.row
// ...other vars?
let imageURL = URL(string: self.posts[row].downloadURL)
cell.myImageView.kf.setImage(with: imageURL) // Using kingfisher for caching and viewing.
// next time, when you will use image with this URL, it will be taken from cache.
// ...other vars?
return cell
}
希望有帮助
我认为您从
firebase
下载图像的方式是错误的
firebase storage
下载图片网址。您需要在 tableCell 中定义一个 imageView`
let imagesRef = FIRStorage.storage().reference()
let imageRef = self.imagesRef.child("imageName.jpg")
imageRef.downloadURL { url, error in
if let error = error {
} else {
DispatchQueue.main.async {
cell.imageView.kf.setImage(with: url)
}
}
}
`
firebase database
下载图像,因为您不能。