前言
UITableView在現(xiàn)如今的APP中已經(jīng)成為必不可少的一個控件,所以今天給大家?guī)鞺ITableView在Swift中是如何實現(xiàn)的,下面這篇文章主要給大家介紹了關(guān)于Swift解決UITableView空數(shù)據(jù)視圖的相關(guān)內(nèi)容,下面話不多說了,來一起看看詳細(xì)的介紹吧
tableView空數(shù)據(jù)問題
一般項目中tableView若數(shù)據(jù)為空時會有一個提示示意圖
為了更好的管理這種提示示意圖,筆者利用extension進(jìn)行了簡單的拓展
解決思路
利用swift面向協(xié)議的特點,使用協(xié)議來進(jìn)行設(shè)置。
具體實現(xiàn)
空視圖協(xié)議,遵守協(xié)議必須實現(xiàn)showEmtpy屬性
private let EmptyViewTag = 12345;protocol EmptyViewProtocol: NSObjectProtocol { ///用以判斷是會否顯示空視圖 var showEmtpy: Bool {get} ///配置空數(shù)據(jù)提示圖用于展示 func configEmptyView() -> UIView?}extension EmptyViewProtocol { func configEmptyView() -> UIView? { return nil }}
tableView擴(kuò)展配置,實現(xiàn)空數(shù)據(jù)示意圖展示判斷
DispatchQueue.once和BQTool.exchangeMethod是只執(zhí)行一次方法交換操作,具體實現(xiàn)可看源碼
func setEmtpyViewDelegate(target: EmptyViewProtocol) { self.emptyDelegate = target DispatchQueue.once(#function) { BQTool.exchangeMethod(cls: self.classForCoder, targetSel: #selector(self.layoutSubviews), newSel: #selector(self.re_layoutSubviews)) } } @objc func re_layoutSubviews() { self.re_layoutSubviews() if self.emptyDelegate!.showEmtpy { guard let view = self.emptyDelegate?.configEmptyView() else { return; } view.tag = EmptyViewTag; self.addSubview(view) } else { guard let view = self.viewWithTag(EmptyViewTag) else { return; } view .removeFromSuperview() } } //MARK:- ***** Associated Object ***** private struct AssociatedKeys { static var emptyViewDelegate = "tableView_emptyViewDelegate" } private var emptyDelegate: EmptyViewProtocol? { get { return (objc_getAssociatedObject(self, &AssociatedKeys.emptyViewDelegate) as! EmptyViewProtocol) } set (newValue){ objc_setAssociatedObject(self, &AssociatedKeys.emptyViewDelegate, newValue!, .OBJC_ASSOCIATION_RETAIN) } }
示例代碼
//關(guān)鍵部分代碼class ViewController: UIViewController , EmptyViewProtocol { private var datas: Array<Dictionary<String, String>>? /// 空數(shù)據(jù)提示圖 private var label: UILabel? var showEmtpy: Bool { get { if let data = self.datas { return data.count == 0 } return true } } override func viewDidLoad() { super.viewDidLoad() let tableView: UITableView = ... tableView.setEmtpyViewDelegate(target: self) self.view.addSubview(tableView) } func configEmptyView() -> UIView? { if let view = self.label { return view } let lab = UILabel(frame: CGRect(x: 100, y: 300, width: 200, height: 30)) lab.text = "this is a test" lab.textAlignment = .center self.label = lab return lab }}
效果圖如下
最后
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點
疑難解答
圖片精選