簡體   English   中英

如何以編程方式將寬高比約束應用於自定義UICollectionViewCell?

[英]How do I apply aspect ratio constraints to a custom UICollectionViewCell programmatically?

我正在嘗試創建一個顯示相冊封面的網格樣式視圖。 我想要每行3張專輯封面。 棘手的部分是根據所使用的設備(例如,iPhone 4s / 5 / 5s / 5c / 6/6 plus)使單元格適當地增加大小,從而無論使用哪種設備,始終每行顯示3個項目/單元格用過的。

我從來沒有能夠做到這一點。 我在考慮手動設置尺寸,如下所示:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if DeviceHelper.DeviceType.IS_IPHONE_4_OR_LESS {
        return CGSizeMake(115, 140)
    } else if DeviceHelper.DeviceType.IS_IPHONE_5 {
        return //size
    } else if DeviceHelper.DeviceType.IS_IPHONE_6 {
        return //size
    } else {
        return //size 
    }
}

我有一個幫助程序,可以確定正在使用的設備,可以在應用程序中的任何位置調用它。 但是,沒有一種方法可以確保無論使用什么設備,每行都始終顯示3個單元格,並且還顯示相同的填充,如下所示:

在此處輸入圖片說明

寬高比限制很有幫助,但是這次我不能將它們應用於單元格,因為接口構建器不允許這樣做。 有沒有直接做到這一點?

在此先感謝您的時間。

刪除默認的單元格間距:

刪除單元格間距

試試這個代碼:

只需為numberOfCellInRow設置值即可收集一行視圖中的單元格數

對象

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
   int numberOfCellInRow = 3;
   CGFloat padding = 5.0;
   CGFloat collectionCellWidth =  [[UIScreen mainScreen] bounds].size.width/numberOfCellInRow;
   CGFloat finalWidthWithPadding = collectionCellWidth - padding;
   return CGSizeMake(finalWidthWithPadding , finalWidthWithPadding);
}

迅速

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    var numberOfCellInRow : Int = 3
    var padding : Int = 5
    var collectionCellWidth : CGFloat = (self.view.frame.size.width/CGFloat(numberOfCellInRow)) - CGFloat(padding)
    return CGSize(width: collectionCellWidth , height: collectionCellWidth)
}

我認為它將適用於所有設備。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM