0

I have 2 elements inside a scrollview.

Element 1 gives out 390.0 after finding its y position using frame.origin.y

As for Element 2, I've attempted to place it in the exact same position as Element 1 (y = 390.0) by writing below :

Element2.frame.origin.y = yPosition

Unfortunately, Element 2 moves upwards only slightly (its was originally far below Element 1) ... it doesn't move to the position given by Element 1 yet the frame.origin.y of both elements are now the same. What could be the problem?

Khan Luke
  • 168
  • 1
  • 13
  • 3
    It's likely that the two elements have a different parent view. Frames are relative. – Tamás Sengel Mar 26 '18 at 12:47
  • @the4kman thanks, they're both inside the scrollview. I honestly don't know how they could both have different parent views. Are bounds relative too? – Khan Luke Mar 26 '18 at 12:49
  • 1
    Bounds are relative to a view's own coordinate system. Read this: https://stackoverflow.com/a/1210141/3151675 – Tamás Sengel Mar 26 '18 at 12:50
  • 2
    Even if they are both inside the scrollview, they can be nested in different UIViews, in that case the frame would be relative to their parent UIView, which may not be the same. If that's the case you can use `element1.convert(element1.frame.origin, to: scrollView)` this will give you the element 1 origin relative to the scrollView – nikano Mar 26 '18 at 12:52
  • Pl Add some code – Prashant Tukadiya Mar 26 '18 at 13:02

2 Answers2

1

The reason is that the frame of the element 1 is not converted to self.view , so it;s relative to the scrollView , not to self.view , You can try

 let ret = self.elem1.convert(self.elem1.frame, to: self.view)

 print(ret.origin.y)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • And how do I get the y-position value? I've tried "ret.frame.origin.y" and it says "Value of type 'CGRect' has no member 'frame" – Khan Luke Mar 26 '18 at 13:01
  • 1
    use rec.origin.y – Shehata Gamal Mar 26 '18 at 13:05
  • Element1.frame.origin.y = (Element2.convert(Element2.frame, to: self.view).origin.y) Tried the above and Element2 is sent way up above Element1. They're both inside the scrollview. I only want them to be in the exact same position. – Khan Luke Mar 26 '18 at 15:01
1

First, convert the scroll view's coordinate to the main view's coordinate perspective. Then, access the the y value through the origin

let ret = self.elem1.convert(self.elem1.frame, to: self.view).origin.y
Andy Obusek
  • 12,614
  • 4
  • 41
  • 62
  • Element1.frame.origin.y = (Element2.convert(Element2.frame, to: self.view).origin.y) Tried the above and Element2 is sent way up above Element1. They're both inside the scrollview. I only want them to be in the exact same position. – Khan Luke Mar 26 '18 at 13:35