If no Table View results, display “No Results” on screen

后端 未结 14 1564
挽巷
挽巷 2020-11-30 17:25

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 the

相关标签:
14条回答
  • 2020-11-30 18:00

    Add this code in one file and change your collection type to 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
      }
    }
    
    0 讨论(0)
  • 2020-11-30 18:02

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

    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.

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

    UIWindow* window = [[UIApplication sharedApplication] keyWindow];
    [window addSubview: OverlayView];
    
    0 讨论(0)
  • 2020-11-30 18:03

    For 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:

    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. Add a UILabel and any constraints to the new view and then create an IBOutlet for that view

    1. Assign that view to the tableView.backgroundView

    1. Behold the magic!

    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.

    0 讨论(0)
  • 2020-11-30 18:03

    Swift Version of above code :-

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

    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
        })
    }
    
    0 讨论(0)
  • 2020-11-30 18:04

    If you want to do this without any code, try this!

    Click on your tableView.

    tableView Screenshot

    Change the style from "plain" to "grouped".

    Table View properties screenshot-2

    Now when you use ....

    tableView.backgroundView = INSERT YOUR LABEL OR VIEW

    It will not show the separators!

    0 讨论(0)
  • 2020-11-30 18:06

    You can easily achieve that by using backgroundView property of 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
    }
    

    Reference UITableView Class Reference

    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.

    0 讨论(0)
提交回复
热议问题