0

Делаю кастовый календарь на UICollectionView. Одна ячейка UICollectionViewCell - одна дата в календаре. Я хочу удалить расстояние между ячейками, чтобы было равно 0. Настройки лейаута -

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: (collectionView.frame.width / 7), height: collectionView.frame.width / 7)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

сториборд

На разных диагоналях, кроме iPhone X, появляется расстояние между ячейками.

issue

Вот, к примеру, iPhone SE -

SE

Как можно решить эту проблему?

2 ответа 2

1

У меня получилось найти решение. В итоге, что получилось: 1.Из сториборда я убрал trailing и leading констреинты, относящиеся к CalendarView. 2. Установил center horizontally на CalendarView и установил констреинт ширины. 3. В ViewController прокинул оутлет констреинта ширины CalendarView 4. viewDidLoad -

let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
let width = self.view.frame.width
let cellSize = CGFloat(width / 7).rounded()
let newWidth = cellSize * 7
layout.itemSize = CGSize(width: cellSize, height: cellSize)
calendarWidth.constant = newWidth
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView.collectionViewLayout = layout

И все стало замечательно работать :)

0

Мне удалось решить аналогичную проблему только путем ручного расчета атрибутов в кастомном классе лейаута, код взят из проекта на Objective C, к сожалению на Swift портировать нет времени, но решение такое же

@interface MyCollectionViewFlowLayout : UICollectionViewFlowLayout

@property (nonatomic) CGFloat maximumCellsSpacing;

@end

Реализация

#import "MyCollectionViewFlowLayout.h"


@implementation MyCollectionViewFlowLayout

- (void)setMaximumCellsSpacing:(CGFloat)maximumCellsSpacing
{
    _maximumCellsSpacing = maximumCellsSpacing;
    self.minimumLineSpacing = maximumCellsSpacing;
    self.minimumInteritemSpacing = maximumCellsSpacing;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *initialLayoutAttributes = [super layoutAttributesForElementsInRect:rect];
    // Fix for "UICollectionViewFlowLayout has cached frame mismatch for index path..."
    // Make deep copy of attributes https://stackoverflow.com/a/33172179/3004003
    NSArray *layoutAttributes = [[NSArray alloc] initWithArray:initialLayoutAttributes copyItems:YES];

    for (NSUInteger i = 1; i < layoutAttributes.count; ++i) {
        UICollectionViewLayoutAttributes *currentLayoutAttributes = layoutAttributes[i];
        UICollectionViewLayoutAttributes *prevLayoutAttributes = layoutAttributes[i - 1];
        CGFloat origin = CGRectGetMaxX(prevLayoutAttributes.frame);

        if (origin + self.maximumCellsSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width && currentLayoutAttributes.frame.origin.x > prevLayoutAttributes.frame.origin.x) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = origin + self.maximumCellsSpacing;
            currentLayoutAttributes.frame = frame;
        }
    }

    return layoutAttributes;
}

@end

Дополнение

Для использования класса его можно указать в сториборд как класс для Collection View Flow Layout, либо назначить программно (collectionView.collectionViewLayout) и потом можно использовать свойство maximumCellsSpacing

12
  • Привет! Спасибо большое за ответ, я перевел на Swift. Но как использовать эти методы?
    – TheGreatVY
    5 июн 2020 в 9:27
  • @TheGreatVY см дополнение к ответу
    – schmidt9
    5 июн 2020 в 9:35
  • А для чего используется метод здесь layoutAttributesForElements? Его как-то реализовывать надо?
    – TheGreatVY
    5 июн 2020 в 10:05
  • @TheGreatVY используется здесь для корректировки положения ячеек, вызывается автоматически, ничего делать не нужно
    – schmidt9
    5 июн 2020 в 10:16
  • Упс, я не заоверрайдил этот метод) Неправильно преобразовал синтаксис.
    – TheGreatVY
    5 июн 2020 в 10:21

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.