Evenly space multiple views within a container view

后端 未结 29 3042
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 06:14

Auto Layout is making my life difficult. In theory, it was going to be really useful when I switched, but I seem to fight it all of the time.

I\'ve made a demo proje

29条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 06:30

    Check out the open source library PureLayout. It offers a few API methods for distributing views, including variants where the spacing between each view is fixed (view size varies as needed), and where the size of each view is fixed (spacing between views varies as needed). Note that all of these are accomplished without the use of any "spacer views".

    From NSArray+PureLayout.h:

    // NSArray+PureLayout.h
    
    // ...
    
    /** Distributes the views in this array equally along the selected axis in their superview. Views will be the same size (variable) in the dimension along the axis and will have spacing (fixed) between them. */
    - (NSArray *)autoDistributeViewsAlongAxis:(ALAxis)axis
                                    alignedTo:(ALAttribute)alignment
                             withFixedSpacing:(CGFloat)spacing;
    
    /** Distributes the views in this array equally along the selected axis in their superview. Views will be the same size (fixed) in the dimension along the axis and will have spacing (variable) between them. */
    - (NSArray *)autoDistributeViewsAlongAxis:(ALAxis)axis
                                    alignedTo:(ALAttribute)alignment
                                withFixedSize:(CGFloat)size;
    
    // ...
    

    Since it's all open source, if you're interested to see how this is achieved without spacer views just take a look at the implementation. (It depends on leveraging both the constant and multiplier for the constraints.)

提交回复
热议问题