Xcode是否具有将加载动画添加到UIImageview的内置方式? UIRefreshControl已经具有旋转动画。可以在加载图片时将该动画用作占位符吗?
答案 0 :(得分:1)
尽管没有没有内置的特定库,但仍有许多第三方可以解决这个问题。
您可以使用uiactivityindicatorview
并创建自定义视图,也可以使用Skeleton View之类的库,该库在图像加载时添加占位符动画。另外,请检查这些other placeholder libraries。
希望这能回答您的问题。
答案 1 :(得分:1)
我认为您可以使用UIActivityIndicatorView来显示图像的加载动画。
let spinner = UIActivityIndicatorView(style: .gray)
spinner.hidesWhenStopped = true
您可以简单地致电
spinner.startAnimating()
是的,您可以使用活动指示器来指示用户正在加载图像。
答案 2 :(得分:0)
在UIImageView
上没有内置的加载动画。您可以如下扩展UIImageView
来添加UIActivityIndicatorView
,
extension UIImageView {
//// Returns activity indicator view centrally aligned inside the UIImageView
private var activityIndicator: UIActivityIndicatorView {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.hidesWhenStopped = true
activityIndicator.color = UIColor.black
self.addSubview(activityIndicator)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
let centerX = NSLayoutConstraint(item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: activityIndicator,
attribute: .centerX,
multiplier: 1,
constant: 0)
let centerY = NSLayoutConstraint(item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: activityIndicator,
attribute: .centerY,
multiplier: 1,
constant: 0)
self.addConstraints([centerX, centerY])
return activityIndicator
}
/// Asynchronous downloading and setting the image from the provided urlString
func setImageFrom(_ urlString: String, completion: (() -> Void)? = nil) {
guard let url = URL(string: urlString) else { return }
let session = URLSession(configuration: .default)
let activityIndicator = self.activityIndicator
DispatchQueue.main.async {
activityIndicator.startAnimating()
}
let downloadImageTask = session.dataTask(with: url) { (data, response, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let imageData = data {
DispatchQueue.main.async {[weak self] in
var image = UIImage(data: imageData)
self?.image = nil
self?.image = image
image = nil
completion?()
}
}
}
DispatchQueue.main.async {
activityIndicator.stopAnimating()
activityIndicator.removeFromSuperview()
}
session.finishTasksAndInvalidate()
}
downloadImageTask.resume()
}
}