2014-01-22 2 views
17

У меня есть UICollectionView, в котором я бы хотел иметь промежуток между ячейками. Тем не менее, несмотря на мои все усилия, я не могу показаться, чтобы удалить пространство,Как удалить границу между двумя столбцами UICollectionView

enter image description here

Код

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section 
{ 
    return 0; 
} 

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section 
{ 
    return 0; 
} 

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section 
{ 
    return UIEdgeInsetsMake(0, 0, 0, 0); 
} 

Дополнительная информация

  • Ширина ячейки составляет 234
  • UICollectionView wi DTH является 703
+1

Подсказка в имени метода, это минимальное расстояние между элементами. CollectionView решит, насколько большой разрыв будет ниже этой суммы. Я думаю, вам нужно будет создать свой собственный UICollectionViewLayout – Tim

+0

Что такое направление прокрутки? –

+0

Я не уверен, что TheMoonlitKnight верна.У меня есть рабочий пример, абсолютно простой, созданный из единого шаблона приложения iPad для iPad с использованием ваших измерений, с макетом расписания по умолчанию, который показывает, что никакой разрыв невозможен и не контролируется с помощью методов ... делегата, которые вы включили выше. Вы зарегистрировали этот код, чтобы убедиться, что он вызван? –

ответ

0

Попробуйте установить 0 (ноль) к свойствам UICollectionView: Min Spacing для клеток и для линий

1

Вы не можете сделать это с помощью по умолчанию UICollectionViewFlowLayout. Хотя вы можете использовать другой макет, например, его подкласс. Я использую этот класс, чтобы установить интервал в явном виде:

@implementation FlowLayoutExt 
@synthesize maxCellSpacing; 

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { 
    NSArray* attributesToReturn = [super layoutAttributesForElementsInRect:rect]; 
    for (UICollectionViewLayoutAttributes* attributes in attributesToReturn) { 
     if (nil == attributes.representedElementKind) { 
      NSIndexPath* indexPath = attributes.indexPath; 
      attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame; 
     } 
    } 
    return attributesToReturn; 
} 

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath { 
    UICollectionViewLayoutAttributes* currentItemAttributes = 
    [super layoutAttributesForItemAtIndexPath:indexPath]; 

    UIEdgeInsets sectionInset = [(UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout sectionInset]; 

    if (indexPath.item == 0) { // first item of section 
//  CGRect frame = currentItemAttributes.frame; 
//  frame.origin.x = sectionInset.left; // first item of the section should always be left aligned 
//  currentItemAttributes.frame = frame; 

     return currentItemAttributes; 
    } 

    NSIndexPath* previousIndexPath = [NSIndexPath indexPathForItem:indexPath.item-1 inSection:indexPath.section]; 
    CGRect previousFrame = [self layoutAttributesForItemAtIndexPath:previousIndexPath].frame; 
    CGFloat previousFrameRightPoint = previousFrame.origin.x + previousFrame.size.width + maxCellSpacing; 

    CGRect currentFrame = currentItemAttributes.frame; 
    CGRect strecthedCurrentFrame = CGRectMake(0, 
               currentFrame.origin.y, 
               self.collectionView.frame.size.width, 
               currentFrame.size.height); 

    if (!CGRectIntersectsRect(previousFrame, strecthedCurrentFrame)) { // if current item is the first item on the line 
     // the approach here is to take the current frame, left align it to the edge of the view 
     // then stretch it the width of the collection view, if it intersects with the previous frame then that means it 
     // is on the same line, otherwise it is on it's own new line 
     CGRect frame = currentItemAttributes.frame; 
     frame.origin.x = sectionInset.left; // first item on the line should always be left aligned 
     currentItemAttributes.frame = frame; 
     return currentItemAttributes; 
    } 

    CGRect frame = currentItemAttributes.frame; 
    frame.origin.x = previousFrameRightPoint; 
    currentItemAttributes.frame = frame; 
    return currentItemAttributes; 
} 
17

От this. Вам необходимо изменить minimumInteritemSpacing и minimumLineSpacing.

UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init]; 
flow.itemSize = CGSizeMake(cellWidth, cellHeight); 
flow.scrollDirection = UICollectionViewScrollDirectionHorizontal; 
flow.minimumInteritemSpacing = 0; 
flow.minimumLineSpacing = 0; 
mainCollectionView.collectionViewLayout = flow; 
+0

Он уже делает это, когда использует метод делегата – kezi

5

Ниже был трюк для меня.

UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init]; 
flow.itemSize = CGSizeMake(360*iPhoneFactorX, 438*iPhoneFactorX); 
flow.scrollDirection = UICollectionViewScrollDirectionHorizontal; 
flow.minimumInteritemSpacing = 0; 
flow.minimumLineSpacing = 0; 


[mainCollectionView reloadData]; 
mainCollectionView.collectionViewLayout = flow; 

Последняя строка очень важна, когда мы присваиваем раскладку

1

Я установил подобную проблему, отключив «Относительно края» в размере инспектора.

enter image description here

Изменить интервал в раскадровке или программно.

enter image description here

или

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

На самом деле, вы не сможете установить параметр для достижения своей цели, используя UICollectionViewFlowLayout, потому что он играет с шагом ячейки, чтобы правильно выровнять все элементы на экране , и именно по этой причине они устанавливают расстояние между ячейками как минимум. Если размер вашей ячейки исправлен, вы можете играть с ViewCollectionSize, чтобы все ячейки и поля идеально вписывались в него.

Смежные вопросы