如果tableView
为空,我将添加“无结果”标签。
extension UITableView {
override open func layoutSubviews() {
print("Table layoutSubviews")
let label = UILabel(frame: self.bounds)
if self.visibleCells.isEmpty {
label.center = self.center
label.text = "No Results"
label.textAlignment = .center
if label.superview == nil {
self.addSubview(label)
}
} else {
label.removeFromSuperview()
}
}
}
但这在更新/重新加载tableView
(行更改)时不起作用。
它在非空UITableView
答案 0 :(得分:2)
extension UITableView {
func setMessage(_ message: String) {
let lblMessage = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
lblMessage.text = message
lblMessage.textColor = .black
lblMessage.numberOfLines = 0
lblMessage.textAlignment = .center
lblMessage.font = UIFont(name: "TrebuchetMS", size: 15)
lblMessage.sizeToFit()
self.backgroundView = lblMessage
self.separatorStyle = .none
}
func clearBackground() {
self.backgroundView = nil
self.separatorStyle = .singleLine
}
}
现在按如下所示使用此扩展名
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if items.count == 0 {
tableView.setMessage("No results")
} else {
tableView.clearBackground()
}
return items.count
}
答案 1 :(得分:0)
创建名称为“ TableViewHelper”的Swift类。 您也可以在CollectionView中使用。
import UIKit
class TableViewHelper {
class func EmptyMessage(message:String, tableview:UITableView,vc:UIViewController) {
let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: vc.view.bounds.size.width, height: vc.view.bounds.size.height))
let messageLabel = UILabel(frame: rect)
messageLabel.text = message
messageLabel.textColor = UIColor.white
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center
messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
messageLabel.sizeToFit()
tableview.backgroundView = messageLabel;
tableview.separatorStyle = .none;
}
}
class ColelctionViewHelper {
class func EmptyMessage(message:String, collectionview:UICollectionView,vc:UIViewController) {
let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: vc.view.bounds.size.width, height: vc.view.bounds.size.height))
let messageLabel = UILabel(frame: rect)
messageLabel.text = message
messageLabel.textColor = UIColor.white
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center
messageLabel.font = UIFont(name: "TrebuchetMS", size: 15)
messageLabel.sizeToFit()
collectionview.backgroundView = messageLabel;
// collectionview.separatorStyle = .none;
}
}
这就是您的使用方式,
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if YourArray.count>0{
TableViewHelper.EmptyMessage(message: "", tableview: TableName,vc: self)
return EventArray.count
}else{
TableViewHelper.EmptyMessage(message: "No Results", tableview: TableName,vc: self)
return 0;
}
}