0

Hi I have searched stack overflow and saw If no Table View results, display "No Results" on screen which is useful but not exactly what i am looking for. My problem is when i follow these steps it works correctly. but if my tableview does end up having data it will flash my "empty tableview label" for a second or 2 before populating my data. It looks terrible in my opinion.

I have a label connected through outlet on my tableview called emptyTableViewlbl. This is my code being called in. Thanks in advance any help is appreciated. Thank you

extension FeedViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if posts.isEmpty {
        emptyTableViewLbl.isHidden = false
        emptyTableViewLbl.text = "Empty tableview label"
        return 0
    } else {
        emptyTableViewLbl.isHidden = true
    }
    return posts.count

}

and have tried

 override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    tableView.delegate = self
    loadPosts()

    if posts.isEmpty {
        emptyTableViewLbl.isHidden = false
        emptyTableViewLbl.text = "Empty"
    } else {
        emptyTableViewLbl.isHidden = true
    }

}
aaron
  • 11
  • 4
  • 3
    Your `numberOfRowsInSection` must not do anything except return a count. It can be called any number of times and at any time. Never update any views or anything else except return a number. – rmaddy May 30 '18 at 02:17
  • 2
    The correct place to show the "empty" label is when `loadPosts` completes with no posts found. – Paulw11 May 30 '18 at 02:33
  • Thankyou @rmaddy for clarifying that considering almost every tutorial/post was saying to check through the numberOfRowsInSection. Can you please give us the correct solution for solving this. Im sure it will help a lot of people thanks! – aaron May 30 '18 at 04:22
  • @Paulw11 Thanks for getting back to me although that makes sense. I do not know if my loadPosts actually has data until it called. Therefore my condition never gets checked. – aaron May 30 '18 at 04:24
  • The comment by @Paulw11 gives the proper solution. Update your "empty" label in `loadPosts` based on the results. – rmaddy May 30 '18 at 04:24

1 Answers1

0

You can use didSet to do so

suppose your array is

var posts:[Post] {
  didSet {
     if posts.isEmpty {
        emptyTableViewLbl.isHidden = false
    } else {
        emptyTableViewLbl.isHidden = true
        tableview.reloadData()
    }
    tableview.isHidden =  !emptyTableViewLbl.isHidden
  }

}
Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98