Swift 4:UITableViewCell初始加载不显示数据,二次加载正常
Hey there, let's tackle this UITableView data loading issue you're facing in your ProfileViewController. I've run into similar headaches before, so here are the most common fixes to get your data showing up on the first load:
1. Make sure you refresh the table after Firebase data is fetched (and on the main thread)
Firebase data calls are asynchronous—just printing to the console doesn't mean the table knows to update. You need to explicitly tell the tableView to reload once your data is ready, and always do UI updates on the main thread (since Firebase callbacks run on a background thread by default).
Here's a quick example with Firestore:
func fetchUserDataFromFirebase() { guard let currentUserUID = Auth.auth().currentUser?.uid else { return } Firestore.firestore().collection("users").document(currentUserUID) .getDocument { [weak self] document, error in guard let self = self else { return } if let error = error { print("Failed to fetch user data: \(error.localizedDescription)") return } // Parse your data into your data source array (adjust this to your model) if let userData = document?.data() { self.userProfileData = UserProfileModel(data: userData) } // Critical: Reload the table on the main thread DispatchQueue.main.async { self.tableView.reloadData() } } }
2. Double-check your tableView's dataSource/delegate connections
It's easy to miss this—either the IB outlets are broken, or you forgot to set them programmatically. Add these lines to your viewDidLoad() to eliminate IB-related issues:
override func viewDidLoad() { super.viewDidLoad() // Explicitly set dataSource and delegate tableView.dataSource = self tableView.delegate = self // Kick off data fetch fetchUserDataFromFirebase() }
3. Verify your data source array is actually populated before reloading
Sometimes the issue isn't the table refresh—it's that your data didn't parse correctly. Add a print statement right before reloading to confirm:
// Inside the Firebase callback print("User profile data loaded: \(self.userProfileData)") // Or check .count if it's an array DispatchQueue.main.async { self.tableView.reloadData() }
If this prints empty or nil, you need to debug your data parsing logic or Firebase query instead.
4. Check your view lifecycle methods
If your data fetch runs in viewDidLoad(), there's a chance the table finishes its initial layout before the data comes back. You can add a safety reload in viewWillAppear(_:) (but avoid redundant fetches):
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Only reload if data exists (prevents unnecessary refreshes) if !userProfileData.isEmpty { DispatchQueue.main.async { self.tableView.reloadData() } } }
5. Rule out cell registration or layout issues
A common gotcha is unregistered cells or broken auto-layout constraints making cells appear invisible. Ensure you're registering your cell correctly in viewDidLoad():
// For code-based cells tableView.register(ProfileTableViewCell.self, forCellReuseIdentifier: "ProfileCell") // For XIB-based cells tableView.register(UINib(nibName: "ProfileTableViewCell", bundle: nil), forCellReuseIdentifier: "ProfileCell")
Also, make sure your cell has proper auto-layout constraints, or enable automatic row heights:
tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 80 // Adjust to match your cell's typical height
Start with the first fix (main thread reload)—that's the most frequent culprit here. If that doesn't work, work your way down the list, and you should have your data showing up on first load in no time!
内容的提问来源于stack exchange,提问作者Chandler Long

