ios CollectionView屏幕等分后出現(xiàn)間隙和排列錯(cuò)亂解決

思路

對(duì)于iPhone 6 Plus之前的手機(jī),pt和px的比例是1:2,而iPhone 6 Plus出來之后,這一比例達(dá)到了1:3,
舉例:一個(gè)collectionView寬度是屏幕寬度 四等分
eg:6s  375 / 4 = 93.75
eg:6P  414 / 4 = 103.5

eg:6s  0.5個(gè)point 是1像素  多余025構(gòu)不成一個(gè)像素
eg:6P  1 / 3個(gè)point是1像素 多余0.166構(gòu)不成一個(gè)像素
只要是整數(shù)后面的小數(shù)是(1 / [UIScreen mainScreen].scale)就行
代碼
- (CGFloat)fixSlitWith:(CGRect)rect colCount:(CGFloat)colCount space:(CGFloat)space {
    CGFloat totalSpace = (colCount - 1) * space;//總間隙
    //每個(gè)item的寬度
    CGFloat itemWidth = (rect.size.width - totalSpace) / colCount;
    CGFloat fixValue = 1 / [UIScreen mainScreen].scale; 
    CGFloat realItemWidth = floor(itemWidth) + fixValue;//取整加fixValue  floor:如果參數(shù)是小數(shù),則求最大的整數(shù)但不大于本身.
    CGFloat realWidth = colCount * realItemWidth + totalSpace;
    //算出屏幕等分后滿足1px=([UIScreen mainScreen].scale)pt實(shí)際的寬度,可能會(huì)超出屏幕,需要調(diào)整一下frame
    CGFloat pointX = (realWidth - rect.size.width) / 2; //偏移距離
    if (pointX > 0) {
        rect.origin.x += pointX;//向左偏移
    }else{
        rect.origin.x -= pointX;//向左偏移
    }
    
    rect.size.width = realWidth;
    self.collectionView.frame = rect;
    [self.collectionView setNeedsLayout];
    return realItemWidth; //每個(gè)cell的真實(shí)寬度
}

參考文章http://www.itdecent.cn/p/01cadd95604d

最后編輯于
?著作權(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ù)。

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