Evenly space multiple views within a container view

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

    Late to the party but I have a working solution for creating a menu horizontally with spacing. It can be easily done using == in NSLayoutConstraint

    const float MENU_HEIGHT = 40;
    
    - (UIView*) createMenuWithLabels: (NSArray *) labels
        // labels is NSArray of NSString
        UIView * backgroundView = [[UIView alloc]init];
        backgroundView.translatesAutoresizingMaskIntoConstraints = false;
    
        NSMutableDictionary * views = [[NSMutableDictionary alloc] init];
        NSMutableString * format = [[NSMutableString alloc] initWithString: @"H:|"];
        NSString * firstLabelKey;
    
        for(NSString * str in labels)
        {
            UILabel * label = [[UILabel alloc] init];
            label.translatesAutoresizingMaskIntoConstraints = false;
            label.text = str;
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor whiteColor];
            [backgroundView addSubview: label];
            [label fixHeightToTopBounds: MENU_HEIGHT-2];
            [backgroundView addConstraints: [label fixHeightToTopBounds: MENU_HEIGHT]];
            NSString * key = [self camelCaseFromString: str];
            [views setObject: label forKey: key];
            if(firstLabelKey == nil)
            {
                [format appendString: [NSString stringWithFormat: @"[%@]", key]];
                firstLabelKey = key;
            }
            else
            {
                [format appendString: [NSString stringWithFormat: @"[%@(==%@)]", key, firstLabelKey]];
            }
        }
    
        [format appendString: @"|"];
    
        NSArray * constraints = [NSLayoutConstraint constraintsWithVisualFormat: (NSString *) format
                                                                                   options: 0
                                                                                   metrics: nil
                                                                                     views: (NSDictionary *) views];
        [backgroundView addConstraints: constraints];
        return backgroundView;
    }
    

提交回复
热议问题