iPhoneの画面サイズに関係なく、2つのセルだけを一列に表示したいのです。
私のストーリーボードにはUICollectionView
、制約によって接続された が含まれています。
さて、これを6秒、5秒、またはそれ以下で実行すると、行に1つのセルだけが表示されます。使用したコードは次のとおりです。
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [categoryImages count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
homePageCells *cell = (homePageCells *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cells" forIndexPath:indexPath];
cell.categoryName.text = [categoryNames objectAtIndex:indexPath.row];
return cell;
}
コードを使用して画面サイズを検出し、適切なセルサイズをプログラムで割り当てようとしましたが、
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize sizes;
CGSize result = [[UIScreen mainScreen] bounds].size;
NSLog(@"%f",result.height);
if(result.height == 480)
{
//Load 3.5 inch xib
sizes =CGSizeMake(170.f, 170.f);
NSLog(@"3gs");
}
else if(result.height == 568)
{
//Load 4 inch xib
sizes =CGSizeMake(130.f, 130.f);
NSLog(@"5s");
}
else if(result.height == 667.000000)
{
//Load 4.7 inch xib
sizes =CGSizeMake(160.f, 160.f);
NSLog(@"6");
}
else
{
NSLog(@"else");
sizes =CGSizeMake(170.f, 165.f);
}
return sizes;
}
しかし、これが正しい方法ではないこともわかっていますので、正しい対処方法を教えてください。
ベストアンサー1
collectionView
セルの幅は幅を使用して計算できるため、デバイスのサイズを確認する必要はありません。セルの幅を使用して、必要に応じて高さを計算できます。
もう1つ:UICollectionViewDelegateFlowLayout
デリゲートを使用して確認し、以下のメソッドを実装する必要があります。
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let padding: CGFloat = 50
let collectionViewSize = collectionView.frame.size.width - padding
return CGSizeMake(collectionViewSize/2, collectionViewSize/2)
}
アップデート: Swift 4.0
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let padding: CGFloat = 50
let collectionViewSize = collectionView.frame.size.width - padding
return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)
}
注記: セルが正方形のサイズであることを考慮して質問に答えました
追加情報:推定サイズがないか確認してくださいhttps://i.sstatic.net/B9kmU.png