[英]how to show my tableview in my popoverController with data
[英]How do I show a return message when there are no data to be displayed in my tableview?
當表格視圖中沒有顯示 email 數據時,我試圖顯示“沒有電子郵件”的返回語句。 然而這無濟於事。 我是否使用了錯誤的變量或 function 調用/類型等? 我該如何解決這個問題?
這些是我嘗試過的代碼,它一直要求我把它放到一個私人函數中而不是發出警告。 即便如此,我仍然無法顯示返回聲明。
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> Any? {
if listOfMessages.count == 0 {
return "There are no messages"
}
return (listOfMessages.count)
}
這是我收到的警告:
實例方法 'tableView( :titleForFooterInSection:)' 幾乎匹配協議 'UITableViewDataSource' 的可選要求 'tableView( :titleForFooterInSection:)'
這些是我在被建議添加 UILabel 並將其屬性設置為 Hidden 之后編寫的新代碼。
func showLabel() {
if listOfMessages.count == 0 {
label.isHidden = true
} else {
label.isHidden = false
}
}
我仍然無法獲得預期的結果。 label 保持隱藏狀態。
將UILabel添加到帶有文本“沒有消息”的視圖中,將其中心設置為視圖的中心,或者您想要顯示它的任何位置。
最初將其isHidden屬性設置為true ,如果
listOfMessages.count == 0
將其isHidden更新為false 。
更新根據您的問題更新更新答案:您的 isHidden 邏輯錯誤,應該是:
func showLabel() {
if listOfMessages.count == 0 {
label.isHidden = true
} else {
label.isHidden = false
}
}
並且不要忘記在更新數據源/重新加載表格視圖時調用 function
你可以使用這個:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if listOfMessages.count == 0{
let emptyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
emptyLabel.text = "There are no messages"
emptyLabel.textAlignment = NSTextAlignment.center
self.tableview.backgroundView = emptyLabel
self.tableview.separatorStyle = .none
return 0
} else {
return listOfMessages.count
}
}
像這樣創建UITableView
的擴展。 在您的UITableView
委托方法中調用此擴展方法。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
items.count == 0 ? tableView.setEmptyMessage("Your message") :
tableView.restore()
return items.count
}
}
extension UITableView {
func setEmptyMessage(_ message: String) {
let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
messageLabel.text = message
messageLabel.textColor = .black
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center;
messageLabel.font = UIFont.systemFont(ofSize: 17)
messageLabel.sizeToFit()
self.backgroundView = messageLabel;
self.separatorStyle = .none;
}
func restore() {
self.backgroundView = nil
self.separatorStyle = .singleLine
}
}
首先,方法tableView(_: titleForFooterInSection:)
只有在tableView
中有任何可見部分時才會調用。
由於所有sections
都有 0 rows
,因此該方法不會執行。
解決方案:
現在,您可以處理它的最簡單方法是在添加tableView
的UIViewController
中添加UILabel
。
現在,您必須使用任何 API 調用來填充您的listOfMessages
array
。 現在,您需要檢查listOfMessages
是否為空,並相應地隱藏/顯示上面添加的label
,而不是簡單地重新加載表。
假設listOfMessages
的類型是[String]
,您可以像這樣在其didSet
觀察者中添加以下代碼,
var listOfMessages = [String]() {
didSet {
label.isHidden = !self.listOfMessages.isEmpty
tableView.reloadData()
}
}
每當listOfMessages
值發生任何變化時,將根據其當前的 state 進行更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.