Masood
Masood

Reputation: 153

Center align multiple UIButtons of varying sizes, dynamically in a UIView

I have an UIView in which I want to add some 'n' buttons of varying sizes dynamically, so normally they get linearly added. Can I center align all the buttons in one go? or do I have to calculations to set the origin of each of the button ?

Here is what I have thought of if I have to do calculations:

Algorithm :

  1. calculate the frame with origins and add a button.
  2. left shift previous buttons to calculated amount
  3. repeat

shifting buttons of varying size becomes very difficult.

Please let me know if there are built in methods that allows me to center align all subviews of a view or should I be doing some maths.

I have stumbled upon some SOF links but seldom of any help

Upvotes: 0

Views: 208

Answers (2)

alicooke
alicooke

Reputation: 118

This code will go through all the subviews of a view and set the x origin so that the subview is centred:

for (UIView *view in yourView.subviews) {
    CGRect newFrame = view.frame;
    newFrame.origin.x = (CGRectGetWidth(myUIView.frame)-CGRectGetWidth(newFrame))/2;
    view.frame = newFrame;
  }

Upvotes: 0

KavyaKavita
KavyaKavita

Reputation: 1579

If you want those buttons evenly spaced and align to center in that case you can use following stack overflow question Link

Upvotes: 1

Related Questions