要实现自定义的 LoadView,类似于 HUD 的效果,可以使用一个单例来管理加载视图的显示和隐藏,并且避免重复添加。以下是一个示例的实现:

首先,创建一个名为 LoadingView 的类,用于显示加载视图。在该类中,你可以使用 SnapKit 来设置约束。

import UIKit
import SnapKit

class LoadingView: UIView {
    
    static let shared = LoadingView()
    
    private var activityIndicatorView: UIActivityIndicatorView!
    
    private init() {
        super.init(frame: .zero)
        
        backgroundColor = UIColor.black.withAlphaComponent(0.5)
        alpha = 0
        
        activityIndicatorView = UIActivityIndicatorView(style: .whiteLarge)
        addSubview(activityIndicatorView)
        
        activityIndicatorView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func show() {
        if let keyWindow = UIApplication.shared.keyWindow {
            keyWindow.addSubview(self)
            
            snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            
            activityIndicatorView.startAnimating()
            
            UIView.animate(withDuration: 0.3) {
                self.alpha = 1
            }
        }
    }
    
    func hide() {
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0
        }) { (_) in
            self.activityIndicatorView.stopAnimating()
            self.removeFromSuperview()
        }
    }
}

然后,在需要显示加载视图的地方,调用 LoadingView.shared.show() 来显示加载视图,调用 LoadingView.shared.hide() 来隐藏加载视图。

例如,在网络请求开始时,调用 LoadingView.shared.show() 显示加载视图,在请求结束时,调用 LoadingView.shared.hide() 隐藏加载视图。

func fetchData() {
    LoadingView.shared.show()
    
    // 发起网络请求
    
    // 请求完成后
    LoadingView.shared.hide()
}

这样,即使有多个网络请求,也只会有一个加载视图显示,并且避免了重复添加的问题。

Swift: 使用自定义 LoadView 实现类似 HUD 的网络加载提示

原文地址: http://www.cveoy.top/t/topic/htJU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录