问题描述
我有UITableView,其中每个单元格都有一个UIImage,并且正在使用JSON从API下载图像。
I have UITableView where each cell has one UIImage and the image is being downloaded from an API using JSON.
我通过后台线程处理了初始图像和数据。但是,当用户在表格视图中向下滚动时,其他单元格的图像开始下载,因此这些单元格需要刷新。
I handled the initial images and data via Background Threading. However, as user scrolls down inside table view, images to other cells begins to download, so those cells requires some refreshing.
我考虑过在UIImageView中添加一个ActivityIndicator,因此用户会注意到正在下载图像。
I thought about adding an ActivityIndicator inside UIImageView, so user will notice image is being downloaded.
附加信息,UIImageView在UIStackView内部。我想到了 isHidden
方法,无法实现。
Additional info, UIImageView is inside an UIStackView. I thought about isHidden
method, could not implemented.
谢谢您的时间。
推荐答案
通常,我建议使用可以为您管理此操作(我相信您可以在加载时设置一个占位符视图以显示),但是如果您要手动执行此操作,则可以使用
Ordinarily I'd recommend using a library like Kingfisher to manage this for you (I believe you can set a placeholder view to display while you're loading) but if you want to do this manually you could have something like
enum LoadingState {
case notLoading
case loading
case loaded(UIImage)
}
class MyTableViewCell: UITableViewCell {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
let imageStackView = UIStackView()
let myImageView = UIImageView() // can't be named imageView because UITableViewCell already has one with that name
var loadingState: LoadingState = .notLoading { // many ways you could do this, you just need one or more "update" mechanisms to start/stop the spinner and set your image
didSet {
switch loadingState {
case .notLoading:
myImageView.image = nil
activityIndicator.stopAnimating()
case .loading:
myImageView.image = nil
activityIndicator.startAnimating()
case let .loaded(img):
myImageView.image = img
activityIndicator.stopAnimating()
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
contentView.addSubview(activityIndicator)
contentView.addSubview(imageStackView)
imageStackView.addArrangedSubview(myImageView)
// constrain activity indicator and stack view
}
override func prepareForReuse() {
super.prepareForReuse()
loadingState = .notLoading
}
}
这篇关于如何使用Swift将ActivityIndicator放在UITableView的UIImage中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!