Search code examples
iosswiftuiviewuiscrollviewscrollview

Get object position within view within scroll view


I have such hierarchy:

  • scroll view
  • --- container view
  • ----- cycle view

enter image description here

This scroll view also can zoom. And I need to show view2 in center of cycle view when I pressed this cycle view(there I have tap gesture recogniser). But view2 should be lye on container view because we also need to zoom it with cycle view.

I try to get rect where need to show view2 with this approach.

func getSourceRect(for cycleView: UIView) -> CGRect {
   let rectOnContainer = cycleView.convert(cycleView.frame, to: containerView)
   let rectOnScrollView = containerView.convert(rectOnContainer, to: scrollView)
        
   return rectOnScrollView
}

and then I do next

let sourceRect = getSourceRect(for: cycleView)
view2.center = CGPoint(x: sourceRect.midX, y: sourceRect.midY)

It doesn't work. Please help me understood this behaviour and get this position where I can show view2


Solution

  • So you want view2 to be centered on the cycle view but attached to the container view?

    If this is true then

    // if view2 and cycle view's parent is container view 
    // then there should not be a need to transform view2's 
    // coordinate space
    view2.center = cycleView.center
    
    // make sure z position is correct so that cycle view isn't obscuring
    // view2's visibility.
    view2.parent?.bringSubviewToFront(view2)