0
我有一個包含圖像的集合視圖。我試圖做的是從單元格獲取圖像的位置,並將它放在與收集單元格拍攝時完全相同的位置。無法獲取單元格內相對於超級視圖的正確位置
這是我最初的CollectionView:
這是挖掘後圖像的位置:
代碼:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.item != 0 {
guard let cell = collectionView.cellForItem(at: indexPath) as? CategoryCell else { return }
selectedImageRect = cell.image.convert(cell.image.frame, to: self.collectionView)
selectedImage = cell.image.image!
}
}
//////
class CategoryAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var selectedImage: UIImage?
var selectedImageRect: CGRect?
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 12.0
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let finalFrameForVC = transitionContext.finalFrame(for: toViewController)
let containerView = transitionContext.containerView
let bounds = UIScreen.main.bounds
toViewController.view.frame = finalFrameForVC.offsetBy(dx: 0, dy: -bounds.size.height)
containerView.addSubview(toViewController.view)
var passedImage = UIImageView(frame: selectedImageRect!)
passedImage.image = selectedImage!
fromViewController.view.addSubview(passedImage)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: .curveLinear, animations: {
fromViewController.view.alpha = 0.5
toViewController.view.frame = finalFrameForVC
}, completion: {
finished in
transitionContext.completeTransition(true)
fromViewController.view.alpha = 1.0
})
}
}
我在做什麼錯?
試試這個:selectedImageRect = cell.image.convert(cell.image.frame,至:self.collectionView.superview) – KKRocks
試試這個:讓theAttributes:UICollectionViewLayoutAttributes! = collectionView.layoutAttributesForItem(at:indexPath) let cellFrameInSuperview:CGRect! = collectionView.convert(theAttributes.frame,to:collectionView.superview)** OR ** selectedImageRect = cell.image.convert(cell.image.frame,to:self.collectionView.superview) – KKRocks