在集合视图单元格的窗口中查找框架

时间:2015-11-21 15:46:05

标签: ios objective-c uicollectionview

我正在UICollectionViewController中获取所有可见的单元格。

NSArray<__kindof UICollectionViewCell *> *cells = [self.collectionView.visibleCells visibleCells];

如何在窗口中找到单元格的框架?

2 个答案:

答案 0 :(得分:6)

试试这个:

<强>夫特

guard
    let indexPath = collectionView.indexPath(for: yourVisibleCell),
    let attributes = collectionView.layoutAttributesForItem(at: indexPath)
    else {
        assertionFailure("Can't get required attributes")
        return
}

let frameInWindow = collectionView.convert(attributes.frame, to: nil)

目标C

NSIndexPath *indexPath = [self.collectionView indexPathForCell:yourVisibleCell];

UICollectionViewLayoutAttributes *theAttributes = [collectionView layoutAttributesForItemAtIndexPath: indexPath];

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

答案 1 :(得分:0)

Xcode友好的Swift变体iPrabu的回答:

var screenCellFrame: CGRect? {
    if let cell = <#visibleCell#>, let indexPath = collectionView?.indexPath(for: cell), let attributes = collectionView!.layoutAttributesForItem(at: indexPath) {
        return collectionView!.convert(attributes.frame, to: nil)
    } else {
        return nil
    }
}