简体   繁体   中英

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

如果您希望这些按钮均匀分布并对齐中心,则可以使用以下堆栈溢出问题链接

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;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM