我正在將我的應用程序重寫爲Swift,並且目前爲止一切正常。但最近我試圖翻譯UICollectionViewFlowLayout子類,並遇到一些問題。我無法理解如何翻譯這個類的layoutAttributesForElementsInRect方法......我只是得到了太多的錯誤。這個班的問題是,這是我沒有寫的單一的。我從互聯網下載了這個課程,所以我不明白它背後的邏輯。誰能幫我?這裏是完整的類,但我只需要layoutAttributesForElementsInRect方法,因爲我已經成功翻譯了第二個(layoutAttributesForItemAtIndexPath)方法。哦,是的!佈局基本上左對齊相應集合視圖中的每個單元格!感謝您的建議!Swift應用程序遷移問題
#import "IYAlignLeftLayout.h"
const NSInteger kMaxCellSpacing = 30;
@implementation IYAlignLeftLayout
- (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 = UIEdgeInsetsMake(50, 20, 50, 20);
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 + kMaxCellSpacing;
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;
}
@end
很抱歉,但它不工作...但也許這只是我的翻譯第二種方法是錯誤的。所以首先我要重新檢查我的layoutAttributesForItemAtIndexPath方法的翻譯。無論如何感謝您的快速響應! –
我找到了解決方案!只需刪除「if let elemedKind = attributes.representedElementKind」條件並且代碼工作得很好!非常感謝您的幫助! –
我剛剛翻譯了您在ObjC中編寫的內容。尚未嘗試過。無論如何高興地知道,可以幫助你 –