developer tip

UICollectionViewCell의 사각형을 얻는 방법은 무엇입니까?

copycodes 2020. 12. 6. 21:41
반응형

UICollectionViewCell의 사각형을 얻는 방법은 무엇입니까?


UITableView메서드 rectForRowAtIndexPath:가 있지만 UICollectionView에 존재하지 않습니다. 셀의 경계 사각형을 잡는 깔끔한 방법을 찾고 있는데, 아마도 UICollectionView.


이 작업을 수행하는 가장 좋은 방법은 다음과 같습니다.

목표 -C

UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];

빠른

let attributes = collectionView.layoutAttributesForItem(at: indexPath)

그런 다음을 통해 해당 위치에 액세스 할 수 있습니다 attributes.frame또는attributes.center


완벽한 프레임을 얻으려면 두 줄의 코드 만 필요합니다.

목표 -C

UICollectionViewLayoutAttributes * theAttributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath];

CGRect cellFrameInSuperview = [collectionView convertRect:theAttributes.frame toView:[collectionView superview]];

스위프트 4.2

let theAttributes = collectionView.layoutAttributesForItem(at: indexPath)
let cellFrameInSuperview = collectionView.convert(theAttributes.frame, to: collectionView.superview)

신속한 3

 let theAttributes:UICollectionViewLayoutAttributes! = collectionView.layoutAttributesForItem(at: indexPath)
 let cellFrameInSuperview:CGRect!  = collectionView.convert(theAttributes.frame, to: collectionView.superview)

신속하게 다음을 수행 할 수 있습니다.

//for any cell in collectionView
let rect = self.collectionViewLayout.layoutAttributesForItemAtIndexPath(clIndexPath).frame

//if you only need for visible cells
let rect = cellForItemAtIndexPath(indexPath)?.frame

어때

-(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

참고 URL : https://stackoverflow.com/questions/12504924/how-to-get-the-rect-of-a-uicollectionviewcell

반응형