【iOS開發(fā)】UICollectionView 只有一個(gè)item時(shí),item居中的解決方法

一個(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)行效果

代碼添加位置:


參考文檔:
http://www.itdecent.cn/p/de08c2679241

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容