iOS Autolayout and UIToolbar/UIBarButtonItems

前端 未结 3 2068
南旧
南旧 2020-12-03 10:07

I have an iOS view with autolayout enabled and have a UIToolbar with a UISearchBar and UISegmentControl contained with the toolbar. I

相关标签:
3条回答
  • 2020-12-03 10:54

    Autolayout constraints only work with UIViews and their subclasses.

    While UIToolbar allows some UIView based items (such as UISearchBar and UISegmentedControl) they may have to coexist with UIBarButtonItems which do not inherit from UIView.

    Until autolayout can work with UIBarButtonItems, do as you have done.

    Your alternative is to roll your own toolbar with widgets based only on UIViews.

    0 讨论(0)
  • 2020-12-03 10:58

    You can do this in code, at least; I'm the type to forsake Interface Builder and go it in code anyway. IB seems to get in my way more often than not when it comes to adding or tweaking constraints. Here's what I've done in my custom UIToolbar subclass's -initWithFrame: method.

    - (instancetype)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            [self addSubview:self.label];
    
            [self addConstraint:[NSLayoutConstraint
                                 constraintWithItem:self.label
                                 attribute:NSLayoutAttributeCenterX
                                 relatedBy:NSLayoutRelationEqual
                                 toItem:self
                                 attribute:NSLayoutAttributeCenterX
                                 multiplier:1 constant:0]];
            [self addConstraint:[NSLayoutConstraint
                                 constraintWithItem:self.label
                                 attribute:NSLayoutAttributeCenterY
                                 relatedBy:NSLayoutRelationEqual
                                 toItem:self
                                 attribute:NSLayoutAttributeCenterY
                                 multiplier:1 constant:0]];
        }
        return self;
    }
    

    And since I like to lazy load as much as possible, here's my self.label instance variable (called when [self addSubview:self.label] gets messaged above).

    - (UILabel *)label {
        if (_label) return _label;
        _label = [UILabel new];
        _label.translatesAutoresizingMaskIntoConstraints = NO;
        _label.textAlignment = NSTextAlignmentCenter;
        return _label;
    }
    

    Seems to work for me. I'm not adding any UIBarButtonItems, though, so your mileage my vary.

    0 讨论(0)
  • 2020-12-03 11:06

    This can also be done right from a storyboard.

    Just drag and drop items in the toolbar, and turn some of them into flexible or fixed space to get the desired effect. See the two examples below.

    Evenly spaced

    Centered

    NB: this is a copy of my answer to Aligning UIToolBar items, I stumbbled upon both questions while looking for such a solution

    0 讨论(0)
提交回复
热议问题