本文主要是介绍[Swift]添加暂无数据和暂无网络缺省页,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Demo
GitHub
每个项目都会对暂无数据和暂无网络进行处理, 提前将这些功能提取出来, 便于以后使用方便.
先pods导入第三方框架,然后拓展控制器的基类.
pod 'EmptyDataSet-Swift', '5.0.0'# 网络监测pod 'ReachabilitySwift'
最后使用时用一句代码解决:
setupEmptyData(scrollView: tableView, reload: true, image: UIImage(named: "icon_qs_data.png"))
示意图:
[代码备份]
下面是模拟的一个列表:
import Foundation
import UIKit
import MJRefreshclass GAHomeVC: BaseVC {@IBOutlet weak var tableView: UITableView!var listArr: [[String: String]] = []var page: Int = 1override func viewDidLoad() {super.viewDidLoad()setupUI()anewReloadData()}func setupUI() {tableView.separatorStyle = .noneadjustsScrollViewInsetNever(scrollView: tableView)setupScrollReload()}override func anewReloadData() {super.anewReloadData()page = 1requestListData()}func setupScrollReload() {let mjheader = MJRefreshNormalHeader { [weak self] inself?.anewReloadData()}mjheader.stateLabel?.textColor = .blackmjheader.lastUpdatedTimeLabel?.isHidden = truetableView.mj_header = mjheaderanewReloadData()let footer = MJRefreshAutoNormalFooter { [weak self] inself?.page += 1self?.requestListData()}footer.isHidden = truefooter.setTitle("暂无更多数据", for: .noMoreData)footer.stateLabel?.textColor = #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 0.5)tableView.mj_footer = footer}@IBAction func tapEmptyAction(_ sender: Any) {tableView.mj_footer?.isHidden = truelistArr.removeAll()page = -1requestListData()}}extension GAHomeVC {func requestListData() {if page == 1 {listArr.removeAll()}let data = moniData()listArr += dataendRefreshing()if data.count < 20 {tableView.mj_footer?.endRefreshingWithNoMoreData()} else {tableView.mj_footer?.resetNoMoreData()}if listArr.count < 20 {tableView.mj_footer?.isHidden = true} else {tableView.mj_footer?.isHidden = false}tableView.reloadData()setupEmptyData(scrollView: tableView, reload: true, image: UIImage(named: "icon_qs_data.png"), space: -70)}func endRefreshing() {if let header = tableView.mj_header , header.isRefreshing {header.endRefreshing()}if let footer = tableView.mj_footer , footer.isRefreshing {footer.endRefreshing()}}func moniData() -> [[String: String]] {if !NetstatManager.shared.isNetworkConnect() {return []}var listCount = 0if page == 1 {listCount = 20} else if page == 2 {listCount = 10} else {return []}var tempArr: [[String: String]] = []for index in ((page-1)*20)..<((page-1)*20+listCount) {let obj = ["title": "title\(index)", "id": "\(index)"]tempArr.append(obj)}return tempArr}}extension GAHomeVC: UITableViewDelegate, UITableViewDataSource {func numberOfSections(in tableView: UITableView) -> Int {return 1}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return listArr.count}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let cell = UITableViewCell(style: .default, reuseIdentifier: "UITableViewCell")cell.selectionStyle = .noneif listArr.count > indexPath.row {let obj = listArr[indexPath.row]cell.textLabel?.text = obj["title"]}return cell}func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {}}
对BaseVC进行功能扩展:
import UIKit
import EmptyDataSet_Swift
import SnapKitclass BaseVC: UIViewController {// 暂无数据 自定义视图var emptyDataCustomView: EmptyDataCustomView?// 暂无网络 自定义视图lazy var netAlert: NetstatAlertVC = {let alert = NetstatAlertVC()alert.modalPresentationStyle = .overCurrentContextalert.modalTransitionStyle = .coverVerticalalert.tranferReloadBlock { [weak self] result inself?.anewReloadData()}return alert}()deinit {NotificationCenter.default.removeObserver(self, name: Notification.Name("NetworkStatusChange"), object: nil)}override func viewDidLoad() {super.viewDidLoad()view.backgroundColor = .systemGray5if #available(iOS 13.0, *) {overrideUserInterfaceStyle = .light} else {// Fallback on earlier versions}}override func viewWillAppear(_ animated: Bool) {super.viewWillAppear(animated)}// MARK: iOS11设置 使用安全区域func adjustsScrollViewInsetNever(scrollView:UIScrollView) {if #available(iOS 11.0, *){scrollView.contentInsetAdjustmentBehavior = .never}else{self.automaticallyAdjustsScrollViewInsets = false}}// MARK: 重新加载刷新数据@objc func anewReloadData() {}}// MARK: 暂无数据/暂无网络
extension BaseVC {/**@abstract 处理暂无数据@param scrollView: 容器@param reload: 是否有刷新按钮@param alert: 提示文字@param image: 提示图片@param space: 文字顶部距离图片底部的相对偏移@param mark: 0表示Size15 #333333, 1表示Size13 #999999@param onlyNet: 方法中只处理暂无网络的提示*/func setupEmptyData(scrollView: UIScrollView?,reload: Bool = false,alert: String = "暂无数据",image: UIImage? = nil,space: CGFloat = 0,mark: Int = 0,onlyNet: Bool = false) {if !NetstatManager.shared.isNetworkConnect() {noNetstatAction(scrollView)return}if onlyNet {return}guard let scr = scrollView else {return}scr.emptyDataSetView { [weak self] view inif self?.emptyDataCustomView == nil {let customView = Bundle.main.loadNibNamed("EmptyDataCustomView", owner: nil, options: nil)![0] as! EmptyDataCustomViewcustomView.setupAlertData(image: image, msg: alert, space: space, mark: mark)if reload {customView.tranferParameterClosure { [weak self] result inself?.anewReloadData()}}self?.emptyDataCustomView = customView}view.customView(self?.emptyDataCustomView).verticalOffset(-50)}}/**@abstract 处理暂无网络@param haveData: 是否有数据@param reload: 是否有刷新按钮*/private func noNetstatAction(_ scrollView: UIScrollView?) {var haveData = falseif let tv = scrollView as? UITableView {let cells = tv.visibleCellsif cells.count > 0 {haveData = true}} else if let co = scrollView as? UICollectionView {let cells = co.visibleCellsif cells.count > 0 {haveData = true}}if !NetstatManager.shared.isNetworkConnect() && haveData == false {NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChange(_:)), name: Notification.Name("NetworkStatusChange"), object: nil)self.view.addSubview(netAlert.view)self.view.bringSubviewToFront(netAlert.view)let top: CGFloat = UIApplication.shared.statusBarFrame.height + 44netAlert.view.snp.remakeConstraints { make inmake.bottom.left.right.equalToSuperview()make.top.equalToSuperview().offset(top)}} else {netAlert.view.removeFromSuperview()}}/// 网络状态从无网络切换到有网络时,通知刷新@objc func networkStatusChange(_ sender: Notification) {noNetstatAction(nil)if let topVC = ScreenUIManager.topViewController() {if topVC.theClassName == self.theClassName {anewReloadData()}}NotificationCenter.default.removeObserver(self, name: Notification.Name("NetworkStatusChange"), object: nil)}}extension NSObject {// 获取对象的类名var theClassName: String {return NSStringFromClass(type(of: self))}
}
暂无数据时的提示视图:
import Foundation
import UIKitclass EmptyDataCustomView: UIView {@IBOutlet weak var alertIV: UIImageView!@IBOutlet weak var ivHConstraint: NSLayoutConstraint!@IBOutlet weak var alertLab: UILabel!@IBOutlet weak var reloadBut: UIButton!@IBOutlet weak var devConstraint: NSLayoutConstraint!private var reloadBlock:((String) -> Void)?override func layoutSubviews() {super.layoutSubviews()}override func awakeFromNib() {super.awakeFromNib()}@IBAction func tapRloadAction(_ sender: Any) {if self.reloadBlock != nil {self.reloadBlock!("刷新了")}}public func tranferParameterClosure(callbackEnclosure:@escaping ((String) -> Void)) {self.reloadBlock = callbackEnclosurereloadBut.isHidden = false}func setupAlertData(image:UIImage?, msg:String, space:CGFloat, mark:Int) {alertIV.image = imagealertLab.text = msgdevConstraint.constant = spaceif mark == 1 {alertLab.textColor = .darkGrayalertLab.font = UIFont.systemFont(ofSize: 13)} else {alertLab.textColor = .blackalertLab.font = UIFont.boldSystemFont(ofSize: 15)}var viewHeight: CGFloat = 100if let ig = image {let igSize = ig.size // 默认都是传的二倍图let newIgSize = CGSize(width: igSize.width/2.0, height: igSize.height/2.0)ivHConstraint.constant = newIgSize.heightviewHeight = viewHeight+newIgSize.height} else {ivHConstraint.constant = 0.0}self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 40, height: viewHeight)}}
网络管理:
import Foundation
import Reachabilityclass NetstatManager: UIViewController {/// 单例static let shared = NetstatManager()/// Reachability必须一直存在,所以需要设置为全局变量let reachability = try! Reachability()lazy var netAlert: NetstatAlertVC = {let alert = NetstatAlertVC()alert.modalPresentationStyle = .overCurrentContextalert.modalTransitionStyle = .coverVerticalreturn alert}()deinit {// 关闭网络状态消息监听reachability.stopNotifier()// 移除网络状态消息通知NotificationCenter.default.removeObserver(self, name: Notification.Name.reachabilityChanged, object: reachability)}override func viewDidLoad() {super.viewDidLoad()}/// 判断是否联网func isNetworkConnect() -> Bool {return reachability.isReachable}}extension NetstatManager {/// 网络状态监听func NetworkStatusListener() {// 1、设置网络状态消息监听 2、获得网络Reachability对象NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),name: Notification.Name.reachabilityChanged,object: reachability)do {// 3、开启网络状态消息监听try reachability.startNotifier()} catch {print("could not start reachability notifier")}}/// 主动监测网络状态@objc func reachabilityChanged(note: NSNotification) {let reachability = note.object as! Reachabilityif reachability.isReachable {if reachability.isReachableViaWiFi {print("连接类型:WiFi")} else {print("连接类型:移动网络")}self.netAlert.dismiss(animated: false, completion: nil)// 由无网络到有网络时才发出通知NotificationCenter.default.post(name: NSNotification.Name("NetworkStatusChange"), object: nil)} else {print("连接类型:暂无网络")self.alert_noNetwrok()}}/// 警告框,提示没有连接网络func alert_noNetwrok() -> Void {if let topVC = ScreenUIManager.topViewController() {if let _ = topVC as? NetstatAlertVC {return}}// UIApplication.shared.keyWindow?.rootViewController?.present(self.netAlert, animated: false, completion: nil)}}
这篇关于[Swift]添加暂无数据和暂无网络缺省页的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!