CollectionView单元格高度问题:仅调整“What's New”单元格高度无效
Hey there, I see you're having trouble getting the height of your "What's New" CollectionView cell to stick after adjusting it in Storyboard—let's break down why this is happening and fix it!
The Root Problem
Your current sizeForItemAt method returns a fixed square size for every cell, no matter what type it is. Even if you set a custom height in Storyboard, this delegate method takes priority and overrides those settings. On top of that, you're trying to modify flowLayout.itemSize inside this method, which isn't necessary (and can cause unexpected layout glitches since this method gets called multiple times during rendering).
The Solution
We need to add a check in sizeForItemAt to identify "What's New" cells and return a custom height for them, while keeping the square size for other cells. Here's how to adjust your code:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // Calculate the base width we want for all cells let baseWidth = (self.view.frame.width - 8) / 3.0 // Replace this with your actual logic to detect "What's New" cells // Example: Check a property in your data model, or a specific indexPath let isWhatsNewCell = /* Your condition here, e.g. dataSource[indexPath.item].type == .whatsNew */ if isWhatsNewCell { // Return your desired height—here we're using 1.5x the width, adjust as needed return CGSize(width: baseWidth, height: baseWidth * 1.5) } else { // Keep the original square size for regular cells return CGSize(width: baseWidth, height: baseWidth) } }
Key Tips to Make This Work:
- Accurate Cell Identification: Make sure your
isWhatsNewCellcondition correctly targets the right cells—this could be based on a data model property, a specific section/index, or checking the cell's class. - Remove Redundant FlowLayout Code: Get rid of the block where you set
flowLayout.itemSizeinside the delegate method. The return value ofsizeForItemAtis what defines each cell's size, so modifying the flow layout here is unnecessary. - Verify Cell Constraints: Ensure your "What's New" cell's contentView has proper constraints (top/bottom/leading/trailing pinned to the contentView) so the content adapts smoothly to the new height.
That should do it! Your "What's New" cells will now use the custom height you want, while other cells stay square as before.
内容的提问来源于stack exchange,提问作者veerendra pratap singh

