Swift 自定义 LoadingView 实现网络请求加载动画
要实现自定义的 LoadingView,可以创建一个自定义的 LoadingView 类,并在其中添加显示和隐藏的方法。然后在网络请求的开始和结束处调用这些方法来显示和隐藏 loading 视图。
首先,创建一个 LoadingView 类,并添加显示和隐藏方法:
import UIKit
class LoadingView: UIView {
static let shared = LoadingView()
private let activityIndicator: UIActivityIndicatorView
private override init(frame: CGRect) {
activityIndicator = UIActivityIndicatorView(style: .large)
activityIndicator.color = .white
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
super.init(frame: frame)
self.backgroundColor = UIColor(white: 0, alpha: 0.5)
self.addSubview(activityIndicator)
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: self.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: self.centerYAnchor)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func show() {
DispatchQueue.main.async {
UIApplication.shared.keyWindow?.addSubview(self)
self.activityIndicator.startAnimating()
}
}
func hide() {
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
self.removeFromSuperview()
}
}
}
然后,在需要显示 loading 视图的地方调用 LoadingView.shared.show() 方法,在请求结束的地方调用 LoadingView.shared.hide() 方法。
示例代码:
func fetchData() {
LoadingView.shared.show()
// 发起网络请求
URLSession.shared.dataTask(with: url) { (data, response, error) in
// 处理请求结果
DispatchQueue.main.async {
LoadingView.shared.hide()
}
}.resume()
}
这样,无论有多少个网络请求,在进行请求时都会显示 loading 视图,请求结束后会隐藏 loading 视图。同时,由于 LoadingView 是一个单例,在整个应用中只会有一个 loading 视图。
原文地址: http://www.cveoy.top/t/topic/htKK 著作权归作者所有。请勿转载和采集!