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

后端 未结 14 1646
挽巷
挽巷 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: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.

提交回复
热议问题