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

后端 未结 14 1641
挽巷
挽巷 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 17:58

    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

    (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)

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

提交回复
热议问题