UITableView
имеет метод rectForRowAtIndexPath:
, но этого не существует в UICollectionView. Я ищу хороший чистый способ захватить прямоугольник с ячейкой, возможно, тот, который я мог бы добавить как категорию на UICollectionView
.
Как получить адрес UICollectionViewCell?
Ответ 1
Лучший способ, который я нашел для этого, заключается в следующем:
Objective-C
UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
стриж
let attributes = collectionView.layoutAttributesForItem(at: indexPath)
Затем вы можете получить доступ к местоположению через attributes.frame
или attributes.center
Ответ 2
Для получения идеального кадра требуется всего две строки кода:
Objective-C
UICollectionViewLayoutAttributes * theAttributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath];
CGRect cellFrameInSuperview = [collectionView convertRect:theAttributes.frame toView:[collectionView superview]];
Swift 4.2
let theAttributes = collectionView.layoutAttributesForItem(at: indexPath)
let cellFrameInSuperview = collectionView.convert(theAttributes.frame, to: collectionView.superview)
Ответ 3
в быстрой 3
let theAttributes:UICollectionViewLayoutAttributes! = collectionView.layoutAttributesForItem(at: indexPath)
let cellFrameInSuperview:CGRect! = collectionView.convert(theAttributes.frame, to: collectionView.superview)
Ответ 4
в быстром режиме:
//for any cell in collectionView
let rect = self.collectionViewLayout.layoutAttributesForItemAtIndexPath(clIndexPath).frame
//if you only need for visible cells
let rect = cellForItemAtIndexPath(indexPath)?.frame
Ответ 5
Как насчет
-(CGRect)rectForCellatIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [self cellForItemAtIndexPath:indexPath];
if (!cell) {
return CGRectZero;
}
return cell.frame;
}
как категория на UICollectionView
?
#import <UIKit/UIKit.h>
@interface UICollectionView (CellFrame)
-(CGRect)rectForCellatIndexPath:(NSIndexPath *)indexPath;
@end
#import "UICollectionView+CellFrame.h"
@implementation UICollectionView (CellFrame)
-(CGRect)rectForCellatIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [self cellForItemAtIndexPath:indexPath];
if (!cell) {
return CGRectZero;
}
return cell.frame;
}
@end