title: How to center a UIView based on the visible part of another view?
body: <p>I'm working on an iOS app in Swift which contains an UIScrollView. The scrollview is "infinite", new elements (subclassed UIViews) are automatically generated on both sides as needed. See <a href="https://developer.apple.com/library/ios/samplecode/StreetScroller/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011102" rel="nofollow noreferrer">here</a> for the example by Apple I based this on.</p>
  
  <p>The view hierarchy:</p>
  
  <pre><code>UIScrollView
  |- viewContainer (UIView containing all the elements in the scrollview)
     |- A 
     |  |- UILabel(hi)
     |
     |- B
     |  |- UILabel(hello)
     |
     |- C
     |  |- UILabel(bonjour)
     |
     |- D
     |  |- UILabel(ciao)
     |
     |- E
     |  |- UILabel(greetings)
  </code></pre>
  
  <p>The subviews A-E each contain a UILabel with some text. As the scrollview moves horizontally, new subviews (F, G, etc) are automatically created.</p>
  
  <p>I'm trying to center the UILabels based on the <em>visible</em> part (the part that the user can actually see) of the elements.</p>
  
  <p><a href="https://i.stack.imgur.com/4BRJJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4BRJJ.jpg" alt="Explanation"></a></p>
  
  <p>See the image above:</p>
  
  <ul>
  <li>(1) Currently elements A, B and C are visible to the user.</li>
  <li>(1) Element B is fully visible, it's label is exactly center.</li>
  <li>(1) However, element C is not fully visible, so it's label moves to the left to make as much of the text visible as possible.</li>
  <li>(2) When the user scrolls the scrollview to the left, new elements become visible.</li>
  <li>(2) As a larger part of element C becomes more visible, more of it's text is displayed. As soon as the entire element is visible, the text centers automatically.</li>
  <li>(3?) If the user would scroll further, and element C would start to drop off the screen on the left side, the label should move to the right side so as to stay visible as long as possible.</li>
  </ul>
  
  <p>All this would happen continuously during scrolling.</p>
  
  <p><strong>Now for the question:</strong>
  How can I make the labels behave in the fashion described above? I have so far been experimenting with overriding <code>layoutSubViews</code> in the elements (A-E). However I have not even been able to extract the part of the elements that is visible to the user. <code>layer.visibleRect</code> seems to give me the entire rectangle, even the portions that are currently offscreen.</p>
  
  <p>Any help or pointers are appreciated!</p>