Search code examples
iosswiftuiviewuistackviewbounds

Get the centre point of UIStackView arranged subviews


I have a custom view inside a UITableViewCell. Inside this view is a simple UIStackView with 4 images (Added programmatically). I need the centre point or the origin of each of these images relative to the UIView superview. I have tried several methods but the centre point or origin is the same for all four arranged subviews.

enter image description here

Here is a simplified code:

for i in 0...3 {
                 
   print(stepsStack.arrangedSubviews[i].frame.origin) //(0,0) for all 4
   print(stepsStack.arrangedSubviews[i].convert(stepsStack.arrangedSubviews[i].frame.origin, to: self)) //(0,0) for all 4
            
   print(stepsStack.arrangedSubviews[i].convert(stepsStack.arrangedSubviews[i].center, to: self)) //(10.0, 9.5) for all 4
   print(stepsStack.convert(stepsStack.arrangedSubviews[i].center, to: self)) //(10.0, 9.5) for all 4
                
 }

Solution

  • Found the solution.

    Called stepsStack.layoutIfNeeded() before calling the above for loop. To be clear, the stack view was added inside the layoutSubviews method of my custom UIView class. Thanks Larme for the hint.