-->

iOS的自动布局和UIToolbar / UIBarButtonItems(iOS Autolayo

2019-07-20 06:09发布

我已经启用了自动布局在iOS视图,并有一个UIToolbar具有UISearchBarUISegmentControl包含与工具栏。 我想要UISearchBar有灵活的宽度,所以我需要添加一个约束,迫使这一点,但我可以告诉你不能在约束添加到项目UIToolbar在Interface Builder。 这些选项都被禁用。

之前AutoLayout我会做到这一点autoresizingmasks

被限制期间不允许UIToolbars/UINavigationBars

还能如何使用自动布局时可能?

Answer 1:

自动布局的限制只能用工作UIViews及其子类。

虽然UIToolbar允许一些UIView基于项目(如UISearchBarUISegmentedControl ),他们可能与共存UIBarButtonItems不继承UIView

直到自动布局可以工作UIBarButtonItems ,做你所做的。

你的选择是与仅基于部件推出自己的工具栏UIViews



Answer 2:

这也可以从一个故事板右侧完成。

只需将工具栏中的掉落物品,并把其中一些为柔性或固定空间,以获得预期的效果。 请参阅下面的两个例子。

注:这是我回答的副本对齐UIToolBar项目 ,我stumbbled在这两个问题而寻找这样一个解决方案



Answer 3:

您可以在代码中做到这一点,至少; 我抛弃接口生成器,去它的代码反正类型。 IB似乎在我的方式获得更多的往往不是当涉及到添加或调整的约束。 这是我在我的自定义所做的UIToolbar子类的-initWithFrame:方法。

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

因为我喜欢懒惰的负载尽可能,这是我self.label实例变量(当叫[self addSubview:self.label]被上述传递消息)。

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

似乎为我工作。 我不加入任何UIBarButtonItems ,虽然如此,你我的里程有所不同。



文章来源: iOS Autolayout and UIToolbar/UIBarButtonItems