Evenly space multiple views within a container view

后端 未结 29 2491
佛祖请我去吃肉
佛祖请我去吃肉 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:28

    Building on Ben Dolman's answer, this distributes the views more evenly (with padding, etc):

    +(NSArray *)constraintsForEvenDistributionOfItems:(NSArray *)views
                               relativeToCenterOfItem:(id)toView vertically:(BOOL)vertically
    {
        NSMutableArray *constraints = [NSMutableArray new];
        NSLayoutAttribute attr = vertically ? NSLayoutAttributeCenterY : NSLayoutAttributeCenterX;
    
        CGFloat min = 0.25;
        CGFloat max = 1.75;
        CGFloat d = (max-min) / ([views count] - 1);
        for (NSUInteger i = 0; i < [views count]; i++) {
            id view = views[i];
            CGFloat multiplier = i * d + min;
            NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:view
                                                                          attribute:attr
                                                                          relatedBy:NSLayoutRelationEqual
                                                                             toItem:toView
                                                                          attribute:attr
                                                                         multiplier:multiplier
                                                                           constant:0];
            [constraints addObject:constraint];
        }
    
        return constraints;
    }
    

提交回复
热议问题