11

Ich implementiere ein benutzerdefiniertes Flow-Layout. Es hat 2 Hauptmethoden zum Überschreiben, um die Platzierung der Zellen zu bestimmen: layoutAttributesForElementsInRect und layoutAttributesForItemAtIndexPath.UICollectionViewLayout layoutAttributesForElementsInRect und layoutAttributesForItemAtIndexPath

In meinem Code wird layoutAttributesForElementsInRect genannt, aber layoutAttributesForItemAtIndexPath ist nicht. Was bestimmt, was aufgerufen wird? Wo wird layoutAttributesForItemAtIndexPath aufgerufen?

Antwort

14

layoutAttributesForElementsInRect: ruft nicht notwendigerweise layoutAttributesForItemAtIndexPath:.

In der Tat, wenn Sie UICollectionViewFlowLayout Unterklasse bilden, wird das Layout das Layout vorbereiten und die resultierenden Attribute zwischenspeichern. Also, wenn layoutAttributesForElementsInRect: aufgerufen wird, fragt es layoutAttributesForItemAtIndexPath: nicht, aber verwendet nur die zwischengespeicherten Werte.

Wenn Sie, dass die Layout-Attribute, um sicherzustellen, wollen immer geändert werden nach Ihrem Layout, implementieren einen Modifikator für beide layoutAttributesForElementsInRect: und layoutAttributesForItemAtIndexPath::

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect 
{ 
    NSArray *attributesInRect = [super layoutAttributesForElementsInRect:rect]; 
    for (UICollectionViewLayoutAttributes *cellAttributes in attributesInRect) { 
    [self modifyLayoutAttributes:cellAttributes]; 
    } 
    return attributesInRect; 
} 

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

- (void)modifyLayoutAttributes:(UICollectionViewLayoutAttributes *)attributes 
{ 
    // Adjust the standard properties size, center, transform etc. 
    // Or subclass UICollectionViewLayoutAttributes and add additional attributes. 
    // Note, that a subclass will require you to override copyWithZone and isEqual. 
    // And you'll need to tell your layout to use your subclass in +(Class)layoutAttributesClass 
} 
+0

Was passiert, wenn ich brauche den Indexpfad die rect Eigenschaft des bestimmen Attribut? Ich habe keine Möglichkeit, den Indexpfad in die Änderungsfunktion zu übergeben. – sudo

+3

Ein 'UICollectionViewLayoutAttributes' hat die Eigenschaft' indexPath'. – Robert

+0

@Robert Gibt [super layoutAttributesForElementsInRect] NULL zurück? Das ist der Eindruck, den ich von den APple-Dokumenten bekommen habe. – moonman239

Verwandte Themen