如果没有 Table 查看结果,则在屏幕上显示 "No Results"
If no Table View results, display "No Results" on screen
我有一个 tableview
,有时可能没有任何结果要列出,所以我 想放一些东西说 "no results"如果没有结果(标签或一个 table 视图单元格?)。
有最简单的方法吗?
我会尝试在 tableview
后面添加 label
,然后根据结果隐藏两者之一,但由于我正在使用 TableViewController
而不是正常的 ViewController
我不确定这有多聪明或可行。
我也在使用 Parse
并将子类化为 PFQueryTableViewController
:
@interface TableViewController : PFQueryTableViewController
我可以提供所需的任何其他详细信息,请告诉我!
TableViewController
情节提要中的场景:
编辑: Per Midhun MP,这是我使用的代码
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numOfSections = 0;
if ([self.stringArray count] > 0)
{
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
//yourTableView.backgroundView = nil;
self.tableView.backgroundView = nil;
}
else
{
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height)];
noDataLabel.text = @"No data available";
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
//yourTableView.backgroundView = noDataLabel;
//yourTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.backgroundView = noDataLabel;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
这是我得到的视图,它仍然有分隔线。我感觉这是一些小改动,但我不确定为什么会出现分隔线?
如果表格视图没有结果,我会提供一个覆盖视图,它具有您想要的外观和消息。您可以在 ViewDidAppear 中执行此操作,因此在 showing/not 显示视图之前您会得到结果。
你可以试试这个控件。它非常整洁。 DZNEmptyDataSet
或者如果我是你我会做的就是
- 检查你的数据数组是否为空
- 如果它是空的,那么添加一个名为@"No Data"的对象到它
- 在 cell.textLabel.text
中显示该字符串
简单易行
我认为解决问题的最优雅方法是从 UITableViewController
切换到包含 UITableView
的 UIViewController
。这样你就可以添加任何你想要的 UIView
作为主视图的子视图。
我不建议使用 UITableViewCell 来执行此操作,您将来可能需要添加其他内容,而且很快就会变得丑陋。
你也可以这样做,但这也不是最好的解决方案。
UIWindow* window = [[UIApplication sharedApplication] keyWindow];
[window addSubview: OverlayView];
您可以使用 backgroundView
属性 或 UITableView
轻松实现。
Objective C:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numOfSections = 0;
if (youHaveData)
{
yourTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
yourTableView.backgroundView = nil;
}
else
{
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, yourTableView.bounds.size.width, yourTableView.bounds.size.height)];
noDataLabel.text = @"No data available";
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
yourTableView.backgroundView = noDataLabel;
yourTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
Swift:
func numberOfSections(in tableView: UITableView) -> Int
{
var numOfSections: Int = 0
if youHaveData
{
tableView.separatorStyle = .singleLine
numOfSections = 1
tableView.backgroundView = nil
}
else
{
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "No data available"
noDataLabel.textColor = UIColor.black
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none
}
return numOfSections
}
backgroundView
Property
The background view of the table view.
Declaration
Swift
var backgroundView: UIView?
Objective-C
@property(nonatomic, readwrite, retain) UIView *backgroundView
Discussion
A table view’s background view is automatically resized to match the
size of the table view. This view is placed as a subview of the table
view behind all cells, header views, and footer views.
You must set this property to nil to set the background color of the
table view.
在您的 numberOfSectionsInTableView
方法中使用此代码:-
if ([array count]==0
{
UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, self.view.frame.size.height/2, 300, 60)];
fromLabel.text =@"No Result";
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor lightGrayColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[fromLabel setFont:[UIFont fontWithName:Embrima size:30.0f]];
[self.view addSubview:fromLabel];
[self.tblView setHidden:YES];
}
Swift 以上代码的版本:-
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var numOfSection: NSInteger = 0
if CCompanyLogoImage.count > 0 {
self.tableView.backgroundView = nil
numOfSection = 1
} else {
var noDataLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
noDataLabel.text = "No Data Available"
noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
noDataLabel.textAlignment = NSTextAlignment.Center
self.tableView.backgroundView = noDataLabel
}
return numOfSection
}
但是如果您从 JSON 加载信息,您需要检查 JSON 是否为空,因此如果您输入这样的代码,它最初会显示 "No data"消息随即消失。因为在 table 重新加载数据后消息隐藏。因此,您可以将此代码放在将 JSON 数据加载到数组的位置。所以:-
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func extract_json(data:NSData) {
var error: NSError?
let jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error)
if (error == nil) {
if let jobs_list = jsonData as? NSArray
{
if jobs_list.count == 0 {
var noDataLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
noDataLabel.text = "No Jobs Available"
noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
noDataLabel.textAlignment = NSTextAlignment.Center
self.tableView.backgroundView = noDataLabel
}
for (var i = 0; i < jobs_list.count ; i++ )
{
if let jobs_obj = jobs_list[i] as? NSDictionary
{
if let vacancy_title = jobs_obj["VacancyTitle"] as? String
{
CJobTitle.append(vacancy_title)
if let vacancy_job_type = jobs_obj["VacancyJobType"] as? String
{
CJobType.append(vacancy_job_type)
if let company_name = jobs_obj["EmployerCompanyName"] as? String
{
CCompany.append(company_name)
if let company_logo_url = jobs_obj["EmployerCompanyLogo"] as? String
{
//CCompanyLogo.append("http://google.com" + company_logo_url)
let url = NSURL(string: "http://google.com" + company_logo_url )
let data = NSData(contentsOfURL:url!)
if data != nil {
CCompanyLogoImage.append(UIImage(data: data!)!)
}
if let vacancy_id = jobs_obj["VacancyID"] as? String
{
CVacancyId.append(vacancy_id)
}
}
}
}
}
}
}
}
}
do_table_refresh();
}
func do_table_refresh() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
Swift3.0
希望能达到你的目的......
在你的 UITableViewController .
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
if filteredContacts.count > 0 {
self.tableView.backgroundView = .none;
return filteredContacts.count
} else {
Helper.EmptyMessage(message: ConstantMap.NO_CONTACT_FOUND, viewController: self)
return 0
}
} else {
if contacts.count > 0 {
self.tableView.backgroundView = .none;
return contacts.count
} else {
Helper.EmptyMessage(message: ConstantMap.NO_CONTACT_FOUND, viewController: self)
return 0
}
}
}
帮助程序 Class 具有以下功能:
/* Description: This function generate alert dialog for empty message by passing message and
associated viewcontroller for that function
- Parameters:
- message: message that require for empty alert message
- viewController: selected viewcontroller at that time
*/
static func EmptyMessage(message:String, viewController:UITableViewController) {
let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: viewController.view.bounds.size.width, height: viewController.view.bounds.size.height))
messageLabel.text = message
let bubbleColor = UIColor(red: CGFloat(57)/255, green: CGFloat(81)/255, blue: CGFloat(104)/255, alpha :1)
messageLabel.textColor = bubbleColor
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center;
messageLabel.font = UIFont(name: "TrebuchetMS", size: 18)
messageLabel.sizeToFit()
viewController.tableView.backgroundView = messageLabel;
viewController.tableView.separatorStyle = .none;
}
SWIFT 3
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "No data available"
noDataLabel.textColor = UIColor.white
noDataLabel.font = UIFont(name: "Open Sans", size: 15)
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none
Swift 3(更新):
override func numberOfSections(in tableView: UITableView) -> Int {
if myArray.count > 0 {
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .singleLine
return 1
}
let rect = CGRect(x: 0,
y: 0,
width: self.tableView.bounds.size.width,
height: self.tableView.bounds.size.height)
let noDataLabel: UILabel = UILabel(frame: rect)
noDataLabel.text = "Custom message."
noDataLabel.textColor = UIColor.white
noDataLabel.textAlignment = NSTextAlignment.center
self.tableView.backgroundView = noDataLabel
self.tableView.separatorStyle = .none
return 0
}
这是对我有用的解决方案。
将以下代码添加到新文件中。
将您的 table class 更改为故事板或 .xib
中的自定义 class "MyTableView"
(这仅适用于第一部分。如果您想自定义更多内容,请针对其他部分相应地更改 MyTableView reloadData() 函数)
public class MyTableView: UITableView {
override public func reloadData() {
super.reloadData()
if self.numberOfRows(inSection: 0) == 0 {
if self.viewWithTag(1111) == nil {
let noDataLabel = UILabel()
noDataLabel.textAlignment = .center
noDataLabel.text = "No Data Available"
noDataLabel.tag = 1111
noDataLabel.center = self.center
self.backgroundView = noDataLabel
}
} else {
if self.viewWithTag(1111) != nil {
self.backgroundView = nil
}
}
}
}
对于Xcode 8.3.2 - Swift 3.1
这是一个不太知名但非常简单的方法,可以将 "No Items" 视图添加到空的 table 视图,该视图可以追溯到 Xcode 7。我将由您控制 adds/removes 视图到 table 的背景视图的逻辑,但这里是 Xcode (8.3.2) 故事板的流程:
- Select 情节提要中具有您 table 视图的场景。
- 将一个空的 UIView 拖到那个场景的"Scene Dock"
- 向新视图添加 UILabel 和任何约束,然后为该视图创建 IBOutlet
- 将该视图分配给 tableView.backgroundView
- 看看魔法吧!
最终,只要您想向视图控制器添加一个您不一定希望立即显示的简单视图,但您也不想手动编写代码,它就可以工作。
如果您不使用 table 视图页脚并且不希望 table 视图用空的默认 table 单元格填满屏幕,我建议您设置您的 table 查看页脚到空的 UIView。我不知道在 obj-c 或 Swift 中执行此操作的正确语法,但在 Xamarin.iOS 中我会这样做:
public class ViewController : UIViewController
{
UITableView _table;
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewWillAppear(bool animated) {
// Initialize table
_table.TableFooterView = new UIView();
}
}
以上代码将生成 table没有空单元格的视图
将此代码添加到一个文件中并将您的集合类型更改为 CustomCollectionView
import Foundation
class CustomCollectionView: UICollectionView {
var emptyModel = EmptyMessageModel()
var emptyView: EmptyMessageView?
var showEmptyView: Bool = true
override func reloadData() {
super.reloadData()
emptyView?.removeFromSuperview()
self.backgroundView = nil
if !showEmptyView {
return
}
if numberOfSections < 1 {
let rect = CGRect(x: 0,
y: 0,
width: self.bounds.size.width,
height: self.bounds.size.height)
emptyView = EmptyMessageView()
emptyView?.frame = rect
if let emptyView = emptyView {
// self.addSubview(emptyView)
self.backgroundView = emptyView
}
emptyView?.setView(with: emptyModel)
} else {
emptyView?.removeFromSuperview()
self.backgroundView = nil
}
}
}
class EmptyMessageView: UIView {
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "EmptyMessageView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
func setView(with model: EmptyMessageModel) {
messageLabel.text = model.message ?? ""
imageView.image = model.image ?? #imageLiteral(resourceName: "no_notification")
}
}
///////////
class EmptyMessageModel {
var message: String?
var image: UIImage?
init(message: String = "No data available", image: UIImage = #imageLiteral(resourceName: "no_notification")) {
self.message = message
self.image = image
}
}
如果您想在没有任何代码的情况下执行此操作,请试试这个!
点击您的 tableView。
将样式从 "plain" 更改为 "grouped"。
现在当你使用....
tableView.backgroundView = 插入您的标签或查看
不会显示分隔符!
我有一个 tableview
,有时可能没有任何结果要列出,所以我 想放一些东西说 "no results"如果没有结果(标签或一个 table 视图单元格?)。
有最简单的方法吗?
我会尝试在 tableview
后面添加 label
,然后根据结果隐藏两者之一,但由于我正在使用 TableViewController
而不是正常的 ViewController
我不确定这有多聪明或可行。
我也在使用 Parse
并将子类化为 PFQueryTableViewController
:
@interface TableViewController : PFQueryTableViewController
我可以提供所需的任何其他详细信息,请告诉我!
TableViewController
情节提要中的场景:
编辑: Per Midhun MP,这是我使用的代码
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numOfSections = 0;
if ([self.stringArray count] > 0)
{
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
//yourTableView.backgroundView = nil;
self.tableView.backgroundView = nil;
}
else
{
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height)];
noDataLabel.text = @"No data available";
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
//yourTableView.backgroundView = noDataLabel;
//yourTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.backgroundView = noDataLabel;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
这是我得到的视图,它仍然有分隔线。我感觉这是一些小改动,但我不确定为什么会出现分隔线?
如果表格视图没有结果,我会提供一个覆盖视图,它具有您想要的外观和消息。您可以在 ViewDidAppear 中执行此操作,因此在 showing/not 显示视图之前您会得到结果。
你可以试试这个控件。它非常整洁。 DZNEmptyDataSet
或者如果我是你我会做的就是
- 检查你的数据数组是否为空
- 如果它是空的,那么添加一个名为@"No Data"的对象到它
- 在 cell.textLabel.text 中显示该字符串
简单易行
我认为解决问题的最优雅方法是从 UITableViewController
切换到包含 UITableView
的 UIViewController
。这样你就可以添加任何你想要的 UIView
作为主视图的子视图。
我不建议使用 UITableViewCell 来执行此操作,您将来可能需要添加其他内容,而且很快就会变得丑陋。
你也可以这样做,但这也不是最好的解决方案。
UIWindow* window = [[UIApplication sharedApplication] keyWindow];
[window addSubview: OverlayView];
您可以使用 backgroundView
属性 或 UITableView
轻松实现。
Objective C:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numOfSections = 0;
if (youHaveData)
{
yourTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
yourTableView.backgroundView = nil;
}
else
{
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, yourTableView.bounds.size.width, yourTableView.bounds.size.height)];
noDataLabel.text = @"No data available";
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
yourTableView.backgroundView = noDataLabel;
yourTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
Swift:
func numberOfSections(in tableView: UITableView) -> Int
{
var numOfSections: Int = 0
if youHaveData
{
tableView.separatorStyle = .singleLine
numOfSections = 1
tableView.backgroundView = nil
}
else
{
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "No data available"
noDataLabel.textColor = UIColor.black
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none
}
return numOfSections
}
backgroundView
PropertyThe background view of the table view.
Declaration
Swift
var backgroundView: UIView?
Objective-C
@property(nonatomic, readwrite, retain) UIView *backgroundView
Discussion
A table view’s background view is automatically resized to match the size of the table view. This view is placed as a subview of the table view behind all cells, header views, and footer views.
You must set this property to nil to set the background color of the table view.
在您的 numberOfSectionsInTableView
方法中使用此代码:-
if ([array count]==0
{
UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, self.view.frame.size.height/2, 300, 60)];
fromLabel.text =@"No Result";
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor lightGrayColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[fromLabel setFont:[UIFont fontWithName:Embrima size:30.0f]];
[self.view addSubview:fromLabel];
[self.tblView setHidden:YES];
}
Swift 以上代码的版本:-
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var numOfSection: NSInteger = 0
if CCompanyLogoImage.count > 0 {
self.tableView.backgroundView = nil
numOfSection = 1
} else {
var noDataLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
noDataLabel.text = "No Data Available"
noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
noDataLabel.textAlignment = NSTextAlignment.Center
self.tableView.backgroundView = noDataLabel
}
return numOfSection
}
但是如果您从 JSON 加载信息,您需要检查 JSON 是否为空,因此如果您输入这样的代码,它最初会显示 "No data"消息随即消失。因为在 table 重新加载数据后消息隐藏。因此,您可以将此代码放在将 JSON 数据加载到数组的位置。所以:-
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func extract_json(data:NSData) {
var error: NSError?
let jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error)
if (error == nil) {
if let jobs_list = jsonData as? NSArray
{
if jobs_list.count == 0 {
var noDataLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
noDataLabel.text = "No Jobs Available"
noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
noDataLabel.textAlignment = NSTextAlignment.Center
self.tableView.backgroundView = noDataLabel
}
for (var i = 0; i < jobs_list.count ; i++ )
{
if let jobs_obj = jobs_list[i] as? NSDictionary
{
if let vacancy_title = jobs_obj["VacancyTitle"] as? String
{
CJobTitle.append(vacancy_title)
if let vacancy_job_type = jobs_obj["VacancyJobType"] as? String
{
CJobType.append(vacancy_job_type)
if let company_name = jobs_obj["EmployerCompanyName"] as? String
{
CCompany.append(company_name)
if let company_logo_url = jobs_obj["EmployerCompanyLogo"] as? String
{
//CCompanyLogo.append("http://google.com" + company_logo_url)
let url = NSURL(string: "http://google.com" + company_logo_url )
let data = NSData(contentsOfURL:url!)
if data != nil {
CCompanyLogoImage.append(UIImage(data: data!)!)
}
if let vacancy_id = jobs_obj["VacancyID"] as? String
{
CVacancyId.append(vacancy_id)
}
}
}
}
}
}
}
}
}
do_table_refresh();
}
func do_table_refresh() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
Swift3.0
希望能达到你的目的...... 在你的 UITableViewController .
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
if filteredContacts.count > 0 {
self.tableView.backgroundView = .none;
return filteredContacts.count
} else {
Helper.EmptyMessage(message: ConstantMap.NO_CONTACT_FOUND, viewController: self)
return 0
}
} else {
if contacts.count > 0 {
self.tableView.backgroundView = .none;
return contacts.count
} else {
Helper.EmptyMessage(message: ConstantMap.NO_CONTACT_FOUND, viewController: self)
return 0
}
}
}
帮助程序 Class 具有以下功能:
/* Description: This function generate alert dialog for empty message by passing message and
associated viewcontroller for that function
- Parameters:
- message: message that require for empty alert message
- viewController: selected viewcontroller at that time
*/
static func EmptyMessage(message:String, viewController:UITableViewController) {
let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: viewController.view.bounds.size.width, height: viewController.view.bounds.size.height))
messageLabel.text = message
let bubbleColor = UIColor(red: CGFloat(57)/255, green: CGFloat(81)/255, blue: CGFloat(104)/255, alpha :1)
messageLabel.textColor = bubbleColor
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center;
messageLabel.font = UIFont(name: "TrebuchetMS", size: 18)
messageLabel.sizeToFit()
viewController.tableView.backgroundView = messageLabel;
viewController.tableView.separatorStyle = .none;
}
SWIFT 3
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "No data available"
noDataLabel.textColor = UIColor.white
noDataLabel.font = UIFont(name: "Open Sans", size: 15)
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none
Swift 3(更新):
override func numberOfSections(in tableView: UITableView) -> Int {
if myArray.count > 0 {
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .singleLine
return 1
}
let rect = CGRect(x: 0,
y: 0,
width: self.tableView.bounds.size.width,
height: self.tableView.bounds.size.height)
let noDataLabel: UILabel = UILabel(frame: rect)
noDataLabel.text = "Custom message."
noDataLabel.textColor = UIColor.white
noDataLabel.textAlignment = NSTextAlignment.center
self.tableView.backgroundView = noDataLabel
self.tableView.separatorStyle = .none
return 0
}
这是对我有用的解决方案。
将以下代码添加到新文件中。
将您的 table class 更改为故事板或 .xib
中的自定义 class "MyTableView"
(这仅适用于第一部分。如果您想自定义更多内容,请针对其他部分相应地更改 MyTableView reloadData() 函数)
public class MyTableView: UITableView {
override public func reloadData() {
super.reloadData()
if self.numberOfRows(inSection: 0) == 0 {
if self.viewWithTag(1111) == nil {
let noDataLabel = UILabel()
noDataLabel.textAlignment = .center
noDataLabel.text = "No Data Available"
noDataLabel.tag = 1111
noDataLabel.center = self.center
self.backgroundView = noDataLabel
}
} else {
if self.viewWithTag(1111) != nil {
self.backgroundView = nil
}
}
}
}
对于Xcode 8.3.2 - Swift 3.1
这是一个不太知名但非常简单的方法,可以将 "No Items" 视图添加到空的 table 视图,该视图可以追溯到 Xcode 7。我将由您控制 adds/removes 视图到 table 的背景视图的逻辑,但这里是 Xcode (8.3.2) 故事板的流程:
- Select 情节提要中具有您 table 视图的场景。
- 将一个空的 UIView 拖到那个场景的"Scene Dock"
- 向新视图添加 UILabel 和任何约束,然后为该视图创建 IBOutlet
- 将该视图分配给 tableView.backgroundView
- 看看魔法吧!
最终,只要您想向视图控制器添加一个您不一定希望立即显示的简单视图,但您也不想手动编写代码,它就可以工作。
如果您不使用 table 视图页脚并且不希望 table 视图用空的默认 table 单元格填满屏幕,我建议您设置您的 table 查看页脚到空的 UIView。我不知道在 obj-c 或 Swift 中执行此操作的正确语法,但在 Xamarin.iOS 中我会这样做:
public class ViewController : UIViewController
{
UITableView _table;
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewWillAppear(bool animated) {
// Initialize table
_table.TableFooterView = new UIView();
}
}
以上代码将生成 table没有空单元格的视图
将此代码添加到一个文件中并将您的集合类型更改为 CustomCollectionView
import Foundation
class CustomCollectionView: UICollectionView {
var emptyModel = EmptyMessageModel()
var emptyView: EmptyMessageView?
var showEmptyView: Bool = true
override func reloadData() {
super.reloadData()
emptyView?.removeFromSuperview()
self.backgroundView = nil
if !showEmptyView {
return
}
if numberOfSections < 1 {
let rect = CGRect(x: 0,
y: 0,
width: self.bounds.size.width,
height: self.bounds.size.height)
emptyView = EmptyMessageView()
emptyView?.frame = rect
if let emptyView = emptyView {
// self.addSubview(emptyView)
self.backgroundView = emptyView
}
emptyView?.setView(with: emptyModel)
} else {
emptyView?.removeFromSuperview()
self.backgroundView = nil
}
}
}
class EmptyMessageView: UIView {
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "EmptyMessageView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
func setView(with model: EmptyMessageModel) {
messageLabel.text = model.message ?? ""
imageView.image = model.image ?? #imageLiteral(resourceName: "no_notification")
}
}
///////////
class EmptyMessageModel {
var message: String?
var image: UIImage?
init(message: String = "No data available", image: UIImage = #imageLiteral(resourceName: "no_notification")) {
self.message = message
self.image = image
}
}
如果您想在没有任何代码的情况下执行此操作,请试试这个!
点击您的 tableView。
将样式从 "plain" 更改为 "grouped"。
现在当你使用....
tableView.backgroundView = 插入您的标签或查看
不会显示分隔符!