一個(gè)UICollectionView的布局問(wèn)題,不常見, 記錄一下解決方案。
一個(gè)collectionView, 設(shè)置了item的UIEdgeInsets 之后, 只有一個(gè)item時(shí),該item居中顯示了,但是有多個(gè)item時(shí),顯示正常:

多個(gè)item時(shí)布局顯示正常

一個(gè)item時(shí)布局顯示居中
檢查了代碼后, 該設(shè)置的行間距,列間距, 以及UIEdgeInsets 都正常:


上網(wǎng)搜了下:UICollectionViewFlowLayout有個(gè)私有方法:- (void)_setRowAlignmentsOptions:(NSDictionary *)options;
該方法中的options,有3個(gè)默認(rèn)的key:
UIFlowLayoutCommonRowHorizontalAlignmentKey //水平對(duì)齊方式
UIFlowLayoutLastRowHorizontalAlignmentKey //當(dāng)前行最后一個(gè)cell的對(duì)齊方式
UIFlowLayoutRowVerticalAlignmentKey //垂直對(duì)齊方式
這3個(gè)key的值為NSTextAlignment的值
UIFlowLayoutCommonRowHorizontalAlignmentKey默認(rèn)值為NSTextAlignmentJustified,意思就是水平分布。
所以當(dāng)UICollectionView 的布局方向?yàn)?UICollectionViewScrollDirectionVertical時(shí), 只有一個(gè)item, 就會(huì)水平居中顯示。
解決方法:
使用runtime改變默認(rèn)值:
SEL sel = NSSelectorFromString(@"_setRowAlignmentsOptions:");
if ([layout respondsToSelector:sel]) {
((void(*)(id,SEL,NSDictionary*)) objc_msgSend)(layout,sel, @{@"UIFlowLayoutCommonRowHorizontalAlignmentKey":@(NSTextAlignmentLeft),@"UIFlowLayoutLastRowHorizontalAlignmentKey" : @(NSTextAlignmentLeft),@"UIFlowLayoutRowVerticalAlignmentKey" : @(NSTextAlignmentCenter)});
}

運(yùn)行效果
代碼添加位置:
