UICollectionViewCell dynamic sizing for 4.4 and 5.5 inch

穿精又带淫゛_ 提交于 2019-12-20 18:58:10

问题


I have UICollectionView with cells in the storyboard. The size of each cell is set to 145x145.

They look good on the iPhone 4 - 5s, but the size doesn't increase proportionally on the iPhone 6 and 6+. Rather than manually setting a different cell size for each device, how can I do it dynamically?

See examples here: iPhone 5S: http://prntscr.com/55vy7q, iPhone 6: http://prntscr.com/55vyy2


回答1:


If you want your cells to adjust their width, you'll need to calculate the flow layout's itemSize based on the view width.

  • If all your cells will be the same size, you can set the flow layout's itemSize property:

    #define kCellsPerRow 2
    
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
    CGFloat availableWidthForCells = CGRectGetWidth(self.collectionView.frame) - flowLayout.sectionInset.left - flowLayout.sectionInset.right - flowLayout.minimumInteritemSpacing * (kCellsPerRow - 1);
    CGFloat cellWidth = availableWidthForCells / kCellsPerRow;
    flowLayout.itemSize = CGSizeMake(cellWidth, flowLayout.itemSize.height);
    

    If you want to dynamically vary the number of cells per row, I've provided those details in a separate answer.

  • If you need to calculate per-cell sizes, you can do it in the collectionView:layout:sizeForItemAtIndexPath: delegate.

Recalculate the itemSize when the device orientation changes and update the layout:

  • Redraw layout without animation:

    [self.collectionView.collectionViewLayout invalidateLayout]

  • Animate layout changes:

    [self.collectionView performBatchUpdates:nil completion:nil]



来源:https://stackoverflow.com/questions/26905191/uicollectionviewcell-dynamic-sizing-for-4-4-and-5-5-inch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!