如何获得细胞的中心点

时间:2016-04-21 07:59:55

标签: swift

每当我点击indexPath.row == 0的单元格时,我想在我的Xib文件中显示AddView

enter image description here

但我不希望它看起来像这样,我希望它从单元格的中心显示indexPath.row == 0(+图像),并以宽度和高度= 1开始,然后它变得越来越大,并进入视图的中心。

怎么做。

这是我目前的代码:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == 0 && addViewIsShowed == false {
            addViewIsShowed = true
            collectionView.alpha = 0.5
            addView.delegate = self
            addView.center = (collectionView.cellForItemAtIndexPath(indexPath)?.contentView.center)!
            addView.frame.size = CGSize(width: 1, height: 1)
            addView.contentView.backgroundColor = UIColor.flatYellowColor()
            view.insertSubview(addView, aboveSubview: collectionView)
            UIView.animateWithDuration(0.8, delay: 0.2, options: [.CurveEaseInOut], animations: {
                self.addView.bounds.size.width = 300
                self.addView.bounds.size.height = 400
                self.addView.center = self.view.center
                }, completion: nil)
        }
    }

更新1

在基于@Zell B指南做基础之后。

代码:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == 0 && addViewIsShowed == false {
            addViewIsShowed = true
            collectionView.alpha = 0.5
            addView.delegate = self
            addView.frame.size = CGSize(width: 1, height: 1)
            let cellContentView = collectionView.cellForItemAtIndexPath(indexPath)?.contentView
            let rect = cellContentView!.convertRect(cellContentView!.frame, toView: self.view)
            addView.center = CGPointMake(rect.origin.x + rect.size.width / 2, rect.origin.y + rect.size.height / 2)
            addView.contentView.backgroundColor = UIColor.flatYellowColor()
            view.insertSubview(addView, aboveSubview: collectionView)
            UIView.animateWithDuration(2.0, delay: 0.2, options: [.CurveEaseInOut], animations: {
                self.addView.bounds.size.width = 120
                self.addView.bounds.size.height = 160
                self.addView.center = self.view.center
                }, completion: nil)
        }
    }

AddView仍未改变大小:

enter image description here

更新2

在动画上方添加addView.clipsToBounds = true之后。它有效。

enter image description here

任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:3)

通过直接从其内容视图获取单元格的中心点,您将获得相对于单元格超级视图的中心,在您的情况下是集合视图。由于UICollectionViewUIScrollView的子类,因为scrollView的contentView会使事情变得复杂,你很难得到理想的点。要简化此问题,您可以轻松地将单元格的帧相对于视图控制器的视图或相对于应用程序窗口进行转换,然后将转换后的点设置为添加的视图。

let cellContentView = collectionView.cellForItemAtIndexPath(indexPath)?.contentView
let rect = cellContentView!.convertRect(cellContentView!.frame, toView: self.view) // pass toView nil if you want to convert rect relative to window
addView.center = CGPointMake(rect.origin.x + rect.size.width / 2, rect.origin.y + rect.size.height / 2)   
相关问题