0

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

Masood
  • 153
  • 8
  • http://stackoverflow.com/questions/33016648/how-can-i-align-3-uibuttons-to-the-center-of-an-uitablecellview/33032552#33032552 this might be helpful – Usama Oct 26 '15 at 12:18
  • If you want to do calculations yourself, using the `center` property looks like the shortest way, otherwise you might want to use autolayout. – A-Live Oct 26 '15 at 12:18
  • 1
    I suggest you to use AutoLayout. – Shial Oct 26 '15 at 12:19
  • @shial: can you help me with some links where to start with ? And also few inputs how will I be doing it. – Masood Oct 26 '15 at 12:22
  • @Masood go for tutorials http://www.raywenderlich.com/115440/auto-layout-tutorial-in-ios-9-part-1-getting-started-2 https://itunesu.itunes.apple.com/WebObjects/LZDirectory.woa/ra/directory/courses/961180099/feed – Shial Oct 26 '15 at 12:39

2 Answers2

1

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

Community
  • 1
  • 1
KavyaKavita
  • 1,581
  • 9
  • 16
0

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;
  }
alicooke
  • 108
  • 1
  • 1
  • 6