简体   繁体   中英

Strange issue with displaying cells in UITableView

I have UITableView with methods:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
override func numberOfSections(in tableView: UITableView) -> Int
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

So, the problem is that Xcode runs at first

override func numberOfSections(in tableView: UITableView) -> Int

which returns me 1. Later it runs override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int which also returns me 1.

BUT I do not know why after these 2 methods it does not run cellForRowAt method and does not display any row on my UITableView.

I do not know what happens there and why this happens. Have you met such problem and could you please help me to fix it?

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let fetchedResultsController = self.fetchedResultsController, let fetchedObjects = fetchedResultsController.fetchedObjects {
        if !searchController.isActive {
            print("numberOfRowsInSection fetchedObjects.count - \(fetchedObjects.count)")
            return fetchedObjects.count
        } else {
            if let results = filteredResult[searchController.searchBar.selectedScopeButtonIndex] {
            print("numberOfRowsInSection results.count - \(results.count)")
                return results.count
            }
        }
    }
    print("numberOfRowsInSection - 0")
    return 0
}

override func numberOfSections(in tableView: UITableView) -> Int {
    if let frc = fetchedResultsController, frc.fetchedObjects?.count != 0 {      
        print("numberOfSections - 1")                              
        return 1
    } else {
        print("numberOfSections - 0")            
        return 0
    }
}

What is probably happening is that your cell has height 0 . When this happens, cellForRowAt won't be called at all, even if the other methods return a non zero section / row count.

My guess as to why this is happening is that you may be using auto layout for your cell, but your constraints don't allow the cell to figure out its own height. You may be using auto layout unknowingly, since on iOS 11, it's now the default. If you are using storyboards you can set the height for the cell prototype on the attributes inspector, instead of checking the automatic box. Alternatively, you can set it in code with tableView.rowHeight or by implementing func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM