Search code examples
iosswiftuicollectionviewuicollectionviewcell

Display popup below selected UICollectionViewCell


I'm working to display popup which should be display below to selected cell.

I have two view controller, both contains UICollectionView. So when I select cell from first view controller I want to display popup with animation exactly below selected cell.

I have tried following code to display it.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    if self.signupFirstStepVC != nil {
        self.signupFirstStepVC?.view.removeFromSuperview()
        self.signupFirstStepVC = nil
    }

    let cell = collectionView.cellForItem(at: indexPath) as! MainCategoryCVC
    collectionView.scrollToItem(at: indexPath, at: .top, animated: true)    
    self.signupFirstStepVC = SignupFirstStepVC.viewController()

    let viewFrame = self.signupFirstStepVC?.view.frame

    self.signupFirstStepVC?.view.frame = CGRect(x: viewFrame!.origin.x, y: cell.lblCategoryName.frame.maxY, width: collectionView.frame.size.width, height: collectionView.frame.size.height - 100)    

    UIView.transition(from: cell, to: self.signupFirstStepVC!.view, duration: 0.5, options: .transitionCrossDissolve) { (success) in
        self.view.addSubview(self.signupFirstStepVC!.view)
    }    
}

This code worked, but not display proper view as I have expected.

Output:

Add Hobbies

You can see in above image, my popup is added, but origin start from UICollectionView's origin instead of cell's lblCategoryName's maxY.

Expected:

Expected Add Hobbies


Solution

  • You need to convert rect according to superview.

    let theAttributes = collectionView.layoutAttributesForItem(at: indexPath)
    let cellFrameInSuperview = collectionView.convert(theAttributes.frame, to: collectionView.superview)
    

    Now you have frame according to its superview.

    set the frame of view controller using cellFrameInSuperview property

    TIP: You should add view controller as child view controller and then add subview to properly manage the view life cycle.

    EDIT

    Please ignore typo

    self.signupFirstStepVC?.view.frame = CGRect(x: cellFrameInSuperview!.origin.x, y: cellFrameInSuperview.maxY, width: collectionView.frame.size.width, height: collectionView.frame.size.height - 100)