Search code examples
iphoneiosuilabelcenteruiactivityindicatorview

How to center a UIActivityIndicatorView along with text (UILabel)?


I've had this issue come up a couple times doing iPhone development now and have yet to find a good solution for it. What I'm looking for is this:

I want to show some text along with an icon and I want the overall display to be centered within its parent view. Specifically, in my current case, I'm looking to display a box that says "Reconnecting..." with a UIActivityIndicatorView to the left of the text.

Previously, I've just relied on the fact that I know exactly the dimensions of the text and activity indicator, so I can position things absolutely to appear centered. What I'm looking for is something more automatic.

Any ideas?


Solution

  • One of the UIKit additions to NSString will return the pixel size of the text if you give it the font that you're using on the UILabel. So then presumably the total size of the two things together in the layout you describe is:

    • the difference between label.frame.origin.x and activityIndicatorView.frame.origin.x; plus
    • the width of the text.

    You can then either shuffle both the views appropriately or give them a common parent that's still a subview of the whole thing and shift that.