Swift 如何把自定义的loadView像HUD那样用于网络加载loading能show能hide并且多个请求只有一个loading视图。怎么写
要实现自定义的loadView,可以创建一个自定义的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视图。
原文地址: https://www.cveoy.top/t/topic/jcbI 著作权归作者所有。请勿转载和采集!