[ios] 如何获取UICollectionViewCell的矩形?



2 Answers

只需要两行代码即可获得完美的帧:

UICollectionViewLayoutAttributes * theAttributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath];

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

UITableView具有rectForRowAtIndexPath:方法,但在UICollectionView中不存在。 我正在寻找一个很好的干净方法来获取单元格的边界矩形,也许我可以在UICollectionView上添加一个类别。




在swift你可以这样做:

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

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



在Swift 4中:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(deviceRotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}

@objc func deviceRotated() {
    if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
        print("Landscape")
    }
    if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
        print("Portrait")
    }
}

它删除了观察者以避免内存泄漏和性能问题。




Related