首页 文章

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

提问于
浏览
99

我有一个 tableview ,有时可能没有任何结果要列出,所以我 would like to put something up that says "no results" 如果没有结果(标签或一个表视图单元?) .

有最简单的方法吗?

我会在 tableview 后面尝试一个 label 然后根据结果隐藏其中一个,但是因为我正在使用 TableViewController 而不是正常的 ViewController 我不确定这是多么聪明或可行 .

我也使用 Parse 并将子类化为 PFQueryTableViewController

@interface TableViewController : PFQueryTableViewController

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

TableViewController Scene in Storyboard:

enter image description here

EDIT: 每个Midhun MP,这里's the code I'米使用

- (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;
}

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

enter image description here

14 回答

  • 7

    您可以使用 UITableViewbackgroundView 属性轻松实现此目的 .

    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
    }
    

    参考UITableView Class Reference

    backgroundView属性表视图的背景视图 . 声明Swift var backgroundView:UIView? Objective-C @property(非原子,读写,保留)UIView * backgroundView讨论表视图的背景视图会自动调整大小以匹配表视图的大小 . 此视图作为所有单元格,页眉视图和页脚视图后面的表视图的子视图放置 . 必须将此属性设置为nil才能设置表视图的背景颜色 .

  • 190

    For Xcode 8.3.2 - Swift 3.1

    这是一个不太知名但非常简单的方法来实现向一个返回Xcode 7的空表视图添加“No Items”视图 . 我将留给你控制添加/删除的逻辑查看表的背景视图,但这里是和Xcode(8.3.2)故事板的流程:

    • 在故事板中选择具有表视图的场景 .

    • 将空的UIView拖到该场景的"Scene Dock"

    enter image description here

    • 将UILabel和任何约束添加到新视图,然后为该视图创建IBOutlet

    enter image description here

    • 将该视图分配给tableView.backgroundView

    enter image description here

    • 看哪!

    enter image description here

    最终,这可以在您想要向视图控制器添加一个简单视图时使用,您不一定要立即显示,但您也不想手动编写代码 .

  • 85

    以上代码的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是否为空,因此如果您放置这样的代码,它最初显示“无数据”消息然后消失 . 因为在表重新加载数据后,消息会隐藏 . 因此,您可以将此代码放在将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
        })
    }
    
  • 5

    你可以试试这个控件 . 它非常整洁 . DZNEmptyDataSet

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

    • 检查数据数组是否为空

    • 如果为空,则向其添加一个名为@ "No Data"的对象

    • 在cell.textLabel.text中显示该字符串

    十分简单

  • 1

    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
    }
    
  • 3

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

    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;
            }
    
  • 1

    我认为解决问题最优雅的方法是从 UITableViewController 切换到包含 UITableViewUIViewController . 这样,您可以添加任何 UIView 作为主视图的子视图 .

    我不建议使用UITableViewCell来执行此操作,您可能需要在将来添加其他内容,并且事情可能会变得非常难看 .

    你也可以这样做,但这也不是最好的解决方案 .

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

    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];
    }
    
  • 1

    这是适合我的解决方案 .

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

    • 将您的表类更改为storyboard或.xib中的自定义类“MyTableView”

    (这仅适用于第一部分 . 如果要自定义更多,请相应地对其他部分进行MyTableView reloadData()函数的更改)

    公共类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
            }
        }
    }
    

    }

  • 3

    如果tableview没有结果,我会提供一个覆盖视图,其中包含您想要的外观和消息 . 您可以在ViewDidAppear中执行此操作,因此您可以在显示/不显示视图之前获得结果 .

  • 1

    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
    
  • 30

    如果您不使用tableview页脚,并且不希望tableview用空默认值填充屏幕表格单元格我建议您将tableview页脚设置为空的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();
        }
    }
    

    上面的代码将导致没有空单元格的tableview

  • 2

    将此代码添加到一个文件中,并将集合类型更改为CustomCollectionView

    进口基金会

    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
    }
    

    }

  • 1

    如果你想在没有任何代码的情况下这样做,试试这个吧!

    点击你的tableView .

    tableView Screenshot

    将样式从“普通”更改为“分组” .

    Table View properties screenshot-2

    现在当你使用....

    tableView.backgroundView =插入您的标签或视图

    它不会显示分隔符!

相关问题