电商APP中UITableView HeightForRowAt行高异常:如何固定text行高为95
Hey there! Let's tackle that frustrating row height issue in your e-commerce app. It sounds like the UITableView is holding onto old row height cache when you switch categories and reload data, which is causing those wonky, extra-tall rows for your "text" cells. Here's how you can lock that row height to 95 permanently:
First, forget trying to set row heights inside cellForRowAt—that's not where row heights are supposed to be controlled. Instead, you need to implement the heightForRowAt delegate method properly. This is the method UITableView relies on to get consistent row heights every time it loads or reloads data.
Here's a code example tailored to your case:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // Grab the current item from your data source (replace with your actual data array) let currentItem = yourCategoryDataSource[indexPath.row] // Check if it's the "text" type cell if currentItem.type == "text" { // Lock this row to exactly 95 points return 95.0 } // For other cell types, return whatever height you need—either a fixed value or automatic dimension return UITableView.automaticDimension // Or a fixed value like 120.0, depending on your design }
Next, make sure you're setting up your table view's estimated row height correctly. If you're using automatic dimension for other cells, a good practice is to set an estimated height that's close to your most common cell size (like 95 for your text cells) to prevent layout jumps and cache issues:
override func viewDidLoad() { super.viewDidLoad() // Set estimated row height (prevents weird caching behavior) tableView.estimatedRowHeight = 95.0 // Let the table view handle automatic dimensions for non-text cells tableView.rowHeight = UITableView.automaticDimension }
If you're still seeing height glitches after switching categories, try wrapping your reload call in beginUpdates() and endUpdates() to force the table view to recalculate all row heights from scratch:
// When you switch categories and update your data source yourCategoryDataSource = newCategoryData tableView.beginUpdates() tableView.reloadData() tableView.endUpdates()
For iOS 15 and later, you can also explicitly clear the row height cache before reloading to eliminate any leftover old height values:
tableView.clearRowHeightCache() tableView.reloadData()
The key takeaway here is to centralize all row height logic in heightForRowAt—this ensures every time the table view reloads (no matter which category is active), it gets the exact height you want for "text" cells, no caching surprises.
内容的提问来源于stack exchange,提问作者user7556668

