iOS UICollectionView - 默认流式布局,从右到左填充行

11

我在我的一个应用程序中使用了UICollectionView,其中包含自定义单元格但默认流程。 目前,该视图以每行3个单元格的方式显示(所有单元格大小相同)。单元格从左到右填充行,但我需要从右到左填充。

这是否可能? 我需要创建自定义流式布局吗? 如果是这样,请问有人能给出简单的例子吗?

非常感谢任何帮助。

3个回答

10

假设您只期望三个单元格,并为此集合视图使用标题视图,则需要执行以下步骤:

覆盖UICollectionViewFlowLayout

@interface GSRightToLeftCollectionViewFlowLayout : UICollectionViewFlowLayout

(GS代表Groboot SmarTech :))

.m文件应该长这样:

#import "GSRightToLeftCollectionViewFlowLayout.h"

typedef enum {
    // enum for comfortibility.
    CellXPositionLeft = 1,
    CellXpositionRight = 2,
    CellXpositionCenter = 3,
    CellXPositionNone = 4
} CellXPosition;

@interface GSRightToLeftCollectionViewFlowLayout ()

@property (nonatomic) BOOL cellFlag;
@property (nonatomic) float cellLeftX;
@property (nonatomic) float cellMiddleX;
@property (nonatomic) float cellRightX;

@end

@implementation GSRightToLeftCollectionViewFlowLayout

// when ever the bounds change, call layoutAttributesForElementsInRect:
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *allItems = [[super layoutAttributesForElementsInRect:rect] mutableCopy];

    for (UICollectionViewLayoutAttributes *attribute in allItems) {

        // when we get an item, calculate it's English writing position,
        // so that we can convert it to the Hebrew - Arabic position.
        if (!self.cellFlag) {

            [self calculateLocationsForCellsWithAttribute:attribute];

            self.cellFlag = YES;
        }

        // if it's a header, do not change it's place.
        if (attribute.representedElementKind == UICollectionElementKindSectionHeader) {

            continue;
        }

        // check where the item should be placed.
        CellXPosition position = [self attributeForPosition:attribute];

        switch (position) {
            case CellXPositionLeft:
                attribute.frame = CGRectMake(self.cellLeftX, attribute.frame.origin.y, attribute.frame.size.width, attribute.frame.size.height);
                break;
            case CellXpositionRight:
                attribute.frame = CGRectMake(self.cellRightX, attribute.frame.origin.y, attribute.frame.size.width, attribute.frame.size.height);
                break;
            case CellXpositionCenter:
                attribute.frame = CGRectMake(self.cellMiddleX, attribute.frame.origin.y, attribute.frame.size.width, attribute.frame.size.height);
                break;
            case CellXPositionNone:
                NSLog(@"warning");
                break;
        }
    }

    return allItems;
}


- (CellXPosition)attributeForPosition:(UICollectionViewLayoutAttributes *)attribute
{
    CellXPosition cellXposition = CellXPositionNone;

    // we will return an opposite answer
    if (attribute.indexPath.row % 3 == 0) {

        // if it's in the left side, move it to the right
        cellXposition = CellXpositionRight;

    } else if (attribute.indexPath.row % 3 == 1) {

        cellXposition = CellXpositionCenter;

    } else if (attribute.indexPath.row % 3) {

        // if it's in the right side, move it to the left
        cellXposition = CellXPositionLeft;
    }

    return cellXposition;
}

- (void)calculateLocationsForCellsWithAttribute:(UICollectionViewLayoutAttributes *)attribute
{
    float cellWidth = self.itemSize.width;
    float minimumX = self.sectionInset.left;
    float maximumX = self.sectionInset.right;
    float displayWidth = self.collectionView.contentSize.width - minimumX - maximumX;
    // on iOS6, displayWidth will be 0 (don't know why), so insert an if (displayWidth == 0) and set manually the size.

    self.cellLeftX = minimumX;
    float space = (displayWidth - cellWidth * 3) / 2;
    self.cellMiddleX = self.cellRightX + cellWidth + space;
    self.cellRightX = self.cellMiddleX + cellWidth + space;
}

@end

在显示CollectionView的类中,您需要执行以下操作:

如果您正在使用storyboard: 1.将collectionView布局更改为自定义(在属性检查器中) 2.将其类设置为GSRightToLeftCollectionViewFlowLayout。 3.在ViewDidLoad(或您执行初始化的任何时间)

- (void)viewDidLoad
{
    [super viewDidLoad];

    GSRightToLeftCollectionViewFlowLayout *layout = [[GSRightToLeftCollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(98, 138); // set the item size.
    layout.minimumLineSpacing = 1; // other layout properties.
    layout.minimumInteritemSpacing = 1; // other layout properties.
    layout.headerReferenceSize = CGSizeMake(50, 18);
    layout.sectionInset = UIEdgeInsetsMake(1.0f, 0.0f, 1.0f, 0.0f);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // in case you use headers / footers. this is also where you would register a Cell if you don't use storyboards.
    [self.collectionView registerClass:[GSReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
    self.collectionView.collectionViewLayout = layout;
}

如果我需要在无限数量的单元格中使用此代码,而且还是水平方向的,那么我需要在代码中做哪些更改? - Leena
@Leena,你能具体说明一下吗? collectionView是水平滚动还是垂直滚动?这段代码并没有限制单元格/项的数量,它只改变了一个项目的属性。你的意思是在一行中有无限数量的项吗?你能上传一下你想要创建的集合视图的可视化表示吗? - Raz
我采用了另一种布局方案,谢谢您的回复。 - Leena
非常有用的答案 - 谢谢!是您提供的示例代码为layoutAttributesForElementsInRect解决了我问题...竟然只要将它向下移动35个像素,天哪! :O - Fattie
@Leena,你能分享一下你的备选方案吗? - iosMentalist

5

由于阿拉伯语的翻译问题,我遇到了相同的问题。

这是我的解决方案:

创建一个UICollectionViewFlowLayout子类并覆盖

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect:

我使用NSLocales字符方向作为RTL翻译的触发器。如果是LTR语言,则仅返回默认属性。

希望这有所帮助。

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *supersAttributes = [super layoutAttributesForElementsInRect:rect];
    NSLocale *currentLocale = ((NSLocale *) [NSLocale currentLocale]);
    NSLocaleLanguageDirection direction = [NSLocale characterDirectionForLanguage:currentLocale.localeIdentifier];

    // if it's an RTL language: change the frame
    if (direction == NSLocaleLanguageDirectionRightToLeft) {
        for (UICollectionViewLayoutAttributes *attributes in supersAttributes) {
            CGRect frame = attributes.frame;
            frame.origin.x = rect.size.width - attributes.frame.size.width - attributes.frame.origin.x;
            attributes.frame = frame;
        }
    }
    return supersAttributes;
}

1
谢谢,先生!我目前遇到的问题是它不再保留单行,而是尝试在新行中添加项目。如果您有任何指针,在我自己研究这个问题的同时,它们将受到赞赏。:) 在可能需要“推送”元素到UICollectionview的情况下,此功能非常有用。 - Jon Madison
1
小细节,但是 supersAttributes 不需要可变性。 - bcattle
当我使用这个时,项目就消失了。我需要做些特殊的事情来让它工作吗?是因为我的视图足够宽,可以滚动吗? - uliwitness

0
@implementation CollectionReversedLayout
- (void)reverseLayoutAttributes:(UICollectionViewLayoutAttributes *)attributes {
     CGPoint newCenter = attributes.center;
     newCenter.x = self.collectionViewContentSize.width - newCenter.x;
     attributes.center = newCenter;
     return attributes;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *s = [super layoutAttributesForElementsInRect:rect];
    for (UICollectionViewLayoutAttributes *attributes in s) {
        [self reverseLayoutAttributes:attributes];
    }
    return s;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *s = [super layoutAttributesForItemAtIndexPath:indexPath];
    [self reverseLayoutAttributes:s];
    return s;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接