IOS - расстояние UICollectionView все еще существует, когда установлено значение 0 - как установить без интервала между ячейками
У меня есть простой UICollectionView, который я установил с 0 интервалом в InterfaceBuilder, но когда я заполняю представление коллекции ячейками, все еще остается некоторое расстояние. Есть ли что-то особенное, и не сразу очевидное, что мне нужно сделать, чтобы реально увидеть ячейку коллекционного представления с интервалом 0 вне его установки равным 0 интервалу? Благодаря.
ОБНОВЛЕНИЕ * некоторый код:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor clearColor];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, cell.frame.size.width -4, cell.frame.size.height -4)];
lbl.backgroundColor = [UIColor clearColor];
lbl.font = [UIFont boldSystemFontOfSize:20];
lbl.text = [NSString stringWithFormat:@"$%0.0f", [[amountsArray objectAtIndex:indexPath.row] floatValue]];
lbl.textAlignment = NSTextAlignmentCenter;
lbl.layer.borderWidth = 1;
[cell addSubview:lbl];
[lbl release];
return cell;
}
![enter image description here]()
Ответы
Ответ 1
Я решил эту проблему и получил желаемый макет со следующим:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor clearColor];
//clear any contents on the cell
for (UIView *subView in [cell subviews]) {
[subView removeFromSuperview];
}
//Label to put on the cell
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, cell.frame.size.width -4, cell.frame.size.height -4)];
lbl.backgroundColor = [UIColor clearColor];
lbl.textColor = [UIColor colorWithRed:[CPExtras RGBtoPercent:70] green:[CPExtras RGBtoPercent:92] blue:[CPExtras RGBtoPercent:105] alpha:1];
lbl.font = [UIFont boldSystemFontOfSize:20];
lbl.text = @"100";
lbl.textAlignment = NSTextAlignmentCenter;
//Give the cell a border
cell.layer.borderColor = [[UIColor colorWithRed:[CPExtras RGBtoPercent:70] green:[CPExtras RGBtoPercent:92] blue:[CPExtras RGBtoPercent:105] alpha:0.5] CGColor];
cell.layer.borderWidth = 0.5;
[cell addSubview:lbl];
[lbl release];
return cell;
}
В IB у меня были эти параметры измерения для коллекции:
![Collection View size]()
![Collection view flow layout size]()
Ответ 2
Простое решение для вашего запроса. Добавьте это в свой файл viewController.m:
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
ProductDetailViewController *HomeVC = [self.storyboard instantiateViewControllerWithIdentifier:@"ProductDetailView"];
HomeVC.title = @"DemoProject";
[self.navigationController pushViewController:HomeVC animated:YES];
}
- (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(0, 0, 0, 0); // top, left, bottom, right
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 0.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
return 0.0;
}
Ответ 3
Вы должны создать пользовательский UICollectionViewLayout
.
Пространство между ячейками будет равно cellSpacing
.
final class CustomFlowLayout: UICollectionViewFlowLayout {
let cellSpacing: CGFloat = 0
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
if let attributes = super.layoutAttributesForElements(in: rect) {
for (index, attribute) in attributes.enumerated() {
if index == 0 { continue }
let prevLayoutAttributes = attributes[index - 1]
let origin = prevLayoutAttributes.frame.maxX
if (origin + cellSpacing + attribute.frame.size.width < self.collectionViewContentSize.width) {
attribute.frame.origin.x = origin + cellSpacing
}
}
return attributes
}
return nil
}
}
Ответ 4
Swift 3 версия @MihirOza решение
Работает как по горизонтали, так и по вертикали.
код
// removing spacing
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, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
Ответ 5
Чтобы иметь нулевое пространство, количество ячеек и их ширина должны быть делятся на собственную ширину коллекции, например
если у вас есть 5 ячеек за раз с шириной 100 пикселей, тогда ваш просмотр коллекции должен иметь ширину 500 пикселей в ширину, если она больше, то она заставит пространство между ячейками.
Ответ 6
documentation для [UICollectionViewFlowLayout minimumInteritemSpacing]
упоминает:
Этот интервал используется для вычисления количества элементов в одной строке, но после определения количества элементов фактический интервал может быть скорректирован вверх.
Для этого может потребоваться реализовать собственный макет. Документацию можно найти здесь, а пример здесь.