ios 如果没有表格视图结果,在屏幕上显示“无结果”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28532926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:50:55  来源:igfitidea点击:

If no Table View results, display "No Results" on screen

iosobjective-cuitableviewparse-platform

提问by SRMR

I have a tableview, where sometimes there might not be any results to list, so I would like to put something up that says "no results"if there are no results (either a label or one table view cell?).

我有一个tableview,有时可能没有任何结果要列出,所以如果没有结果(标签或一个表格视图单元格?),我想放一些说“没有结果”的东西

Is there an easiest way to do this?

有没有最简单的方法来做到这一点?

I would try a labelbehind the tableviewthen hide one of the two based on the results, but since I'm working with a TableViewControllerand not a normal ViewControllerI'm not sure how smart or doable that is.

我会尝试在label后面tableview然后根据结果隐藏两者之一,但由于我使用的是 aTableViewController而不是正常的,ViewController我不确定这有多聪明或可行。

I'm also using Parseand subclassing as a PFQueryTableViewController:

我也在使用Parse和子类化为PFQueryTableViewController

@interface TableViewController : PFQueryTableViewController

I can provide any additional details needed, just let me know!

我可以提供所需的任何其他详细信息,请告诉我!

TableViewControllerScene in Storyboard:

TableViewController故事板中的场景:

enter image description here

在此处输入图片说明

EDIT:Per Midhun MP, here's the code I'm using

编辑:根据 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;
}

And here's the View I'm getting, it still has separator lines. I get the feeling that this is some small change, but I'm not sure why separator lines are showing up?

这是我得到的视图,它仍然有分隔线。我觉得这是一些小的变化,但我不确定为什么会出现分隔线?

enter image description here

在此处输入图片说明

回答by Midhun MP

You can easily achieve that by using backgroundViewproperty of UITableView.

您可以通过使用 的backgroundView属性轻松实现这一点UITableView

Objective C:

目标 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
}


Reference UITableView Class Reference

参考UITableView 类参考

backgroundViewProperty

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.

backgroundView财产

表视图的背景视图。

宣言

迅速

var backgroundView: UIView?

目标-C

@property(nonatomic, readwrite, retain) UIView *backgroundView

讨论

表视图的背景视图会自动调整大小以匹配表视图的大小。此视图作为表格视图的子视图放置在所有单元格、页眉视图和页脚视图之后。

您必须将此属性设置为 nil 以设置表格视图的背景颜色。

回答by Paul Bonneville

For Xcode 8.3.2 - Swift 3.1

对于 Xcode 8.3.2 - Swift 3.1

Here is a not-so-well-known but incredibly easy way to achieve adding a "No Items" view to an empty table view that goes back to Xcode 7. I'll leave it to you control that logic that adds/removes the view to the table's background view, but here is the flow for and Xcode (8.3.2) storyboard:

这是一个不太知名但非常简单的方法来实现将“No Items”视图添加到可追溯到 Xcode 7 的空表视图。我将让您控制添加/删除查看表格的背景视图,但这里是 Xcode (8.3.2) 故事板的流程:

  1. Select the scene in the Storyboard that has your table view.
  2. Drag an empty UIView to the "Scene Dock" of that scene
  1. 在 Storyboard 中选择具有表视图的场景。
  2. 将一个空的 UIView 拖到该场景的“场景码头”

enter image description here

在此处输入图片说明

  1. Add a UILabel and any constraints to the new view and then create an IBOutlet for that view
  1. 向新视图添加 UILabel 和任何约束,然后为该视图创建一个 IBOutlet

enter image description here

在此处输入图片说明

  1. Assign that view to the tableView.backgroundView
  1. 将该视图分配给 tableView.backgroundView

enter image description here

在此处输入图片说明

  1. Behold the magic!
  1. 看魔术!

enter image description here

在此处输入图片说明

Ultimately this works anytime you want to add a simple view to your view controller that you don't necessarily want to be displayed immediately, but that you also don't want to hand code.

最终,只要您想向您的视图控制器添加一个简单的视图,您不一定希望立即显示该视图,但您也不想手动编写代码,这就会起作用。

回答by Chathuranga Silva

Swift Version of above code :-

上面代码的 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
}

But If you are loading Information From a JSON , you need to check whether the JSON is empty or not , therefor if you put code like this it initially shows "No data" Message then disappear. Because after the table reload data the message hide. So You can put this code where load JSON data to an array. SO :-

但是,如果您从 JSON 加载信息,则需要检查 JSON 是否为空,因此,如果您输入这样的代码,它最初会显示“无数据”消息,然后消失。因为在表重新加载数据后消息隐藏。因此,您可以将此代码放在将 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
    })
}

回答by Sam B

You can try this control. Its is pretty neat. DZNEmptyDataSet

你可以试试这个控件。它非常整洁。DZN空数据集

Or if I were you all I would do is

或者如果我是你,我会做的就是

  • Check to see if your data array is empty
  • If it is empty then add one object called @"No Data" to it
  • Display that string in cell.textLabel.text
  • 检查您的数据数组是否为空
  • 如果它为空,则向其添加一个名为@"No Data"的对象
  • 在 cell.textLabel.text 中显示该字符串

Easy peasy

十分简单

回答by Ravindra Shekhawat

Swift3.0

斯威夫特3.0

I hope it server your purpose...... In your UITableViewController .

我希望它服务于你的目的......在你的 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
        }
    }
}

Helper Class with function :

具有功能的助手类:

 /* 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;
        }

回答by Teodor Ciuraru

Swift 3 (updated):

斯威夫特 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
}

回答by Chandan

Use this code in Your numberOfSectionsInTableViewmethod:-

在您的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];
}

回答by Cihan Tek

I think the most elegant way to solve your problem is switching from a UITableViewControllerto a UIViewControllerthat contains a UITableView. This way you can add whatever UIViewyou want as subviews of the main view.

我认为解决您的问题最优雅的方法是从 a 切换UITableViewControllerUIViewController包含UITableView. 这样你就可以添加任何UIView你想要的作为主视图的子视图。

I wouldn't recommend using a UITableViewCell to do this you might need to add additional things in the future and things can quicky get ugly.

我不建议使用 UITableViewCell 来执行此操作,您将来可能需要添加其他内容,并且事情很快就会变得丑陋。

You can also do something like this, but this isn't the best solution either.

您也可以执行类似的操作,但这也不是最佳解决方案。

UIWindow* window = [[UIApplication sharedApplication] keyWindow];
[window addSubview: OverlayView];

回答by Ahmed Safadi

SWIFT 3

斯威夫特 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

回答by ShrikantWalekar

Here is the solution that worked for me.

这是对我有用的解决方案。

  1. Add the following code to a new file.

  2. Change your table class to the custom class "MyTableView" from storyboard or .xib

  1. 将以下代码添加到新文件中。

  2. 将您的表类从故事板或 .xib 更改为自定义类“MyTableView”

(this will work for the first section only. If you want to customize more, do changes in the MyTableView reloadData() function accordingly for other sections)

(这仅适用于第一部分。如果您想自定义更多,请对其他部分相应地更改 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
            }
        }
    }
}