如何在模态呈现的viewController中获取UIView的位置

时间:2014-12-18 23:41:31

标签: ios objective-c iphone swift

我正在使用自定义presentationStyle呈现一个viewcontroller。父Controller是一个UICollectionViewController。在我的UICollectionViewController的didSelectAtIndexPath方法中,我将获取所选单元格的UIImageView并将其设置为动态呈现的视图控件中UIView框架的位置。

如何获得模态呈现的viewcontroller的UIView框架?

self.imageView!.frame = trophyOverlayVC.trophyImageLocationView!.frame  

不起作用。

在大多数情况下,它出现在屏幕外。

import UIKit

class CollectionHolderViewController: MainPageContentViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    [..insert other methods here..]

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as TrophyCollectionViewCell

        self.collectionViewController.collectionView!.scrollEnabled = false // disable scrolling so view won't move
        self.collectionViewController.collectionView!.userInteractionEnabled = false
        let innerOffset = collectionView.contentOffset as CGPoint // offset of content view due to scrolling
        let attributes = self.collectionViewController.collectionView!.layoutAttributesForItemAtIndexPath(indexPath) as UICollectionViewLayoutAttributes!
        let cellRect = attributes.frame // frame of cell in contentView

        imageView = UIImageView(frame: CGRectMake(cellRect.origin.x, cellRect.origin.y, cellRect.size.width, cellRect.size.height)) //places image in location of collectionViewCell.
        imageView!.image = UIImage(named: placeHolderArray[indexPath.row]) //change.
        imageView!.contentMode = UIViewContentMode.ScaleAspectFit

        self.collectionViewController.collectionView!.addSubview(imageView!)


        self.placeHolderArray[indexPath.row] = ""
        UIView.setAnimationsEnabled(false)
        self.collectionViewController.collectionView!.reloadItemsAtIndexPaths([indexPath])
        UIView.setAnimationsEnabled(true)

        var trophyOverlayVC = self.collectionViewController.storyboard!.instantiateViewControllerWithIdentifier("TrophyOverlayVC") as TrophyOverlayViewController
        trophyOverlayVC.modalPresentationStyle = UIModalPresentationStyle.Custom
        self.presentViewController(trophyOverlayVC, animated: false, completion: self.presentViewController(trophyOverlayVC, animated: false, completion: { (value: Void) in UIView.animateWithDuration(0.5, animations: {
        self.imageView!.frame = trophyOverlayVC.trophyImageLocationView!.frame
        }, completion: {
            (value: Bool) in
    }) })
}

1 个答案:

答案 0 :(得分:1)

不要试图立即为其设置动画,而是在presentViewController完成块(您当前正在传递nil的位置)内执行此操作。此时,所有frame都将正确设置。

此外,这种方法只有在他们的超级视图以相同的方式放置在坐标系中时才有效。请记住,框架的origin(以及视图的center)是与其超级视图相关的坐标 。如果它们不相同,则您需要使用UIView的{​​{1}}或convertRect(_:toView:)将矩形转换为相应视图的坐标系。