[FIXED] UICollectionViewZellengröße für 3 Elemente pro Zeile

Ausgabe

Ich versuche, eine UICollectionViewmit 3 Bildern pro Zeile zu erstellen.

Für den Anfang habe ich diesen Code verwendet:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(110, 110);
}

Und es sieht gut aus, passt aber nur auf den Bildschirm des iPhone X:
Geben Sie hier die Bildbeschreibung ein

Dann habe ich versucht, diesen Code zu verwenden, damit 3 Zellen pro Zeile eingefügt werden:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    float cellWidth = screenWidth / 3.0;
    CGSize size = CGSizeMake(cellWidth, cellWidth);

    return size;
}

Aber dann sieht die Aussicht anders aus:
Geben Sie hier die Bildbeschreibung ein

Dies ist die Zelleninitialisierungsmethode:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
              cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"TrendingCell";

TrendingCell *cell = (TrendingCell*)[collection dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

TrendingItem * item = [[[TrendingRep sharedTrending] trendingArray] objectAtIndex:indexPath.row];

cell.text.text = item.title;

cell.image.layer.cornerRadius = cell.image.frame.size.width / 2;
cell.image.clipsToBounds = YES;

[cell.image sd_setImageWithURL:[NSURL URLWithString:item.imageUrl]
               placeholderImage:nil
                        options:SDWebImageProgressiveDownload
                      completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {

                          [cell.progressView setHidden:NO];
}];

return cell;
}

Irgendeine Idee, was das Problem mit der Ansicht sein kann?

Lösung

Dies sieht so aus, als würden Sie das Layout nicht berücksichtigen minimumInteritemSpacing. Die Formel zur Berechnung der Artikelbreite sollte lauten

float cellWidth = (screenWidth - 2.0 * minimumInteritemSpacing) / 3.0;


Beantwortet von –
Gereon


Antwort geprüft von –
Willingham (FixError Volunteer)

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like