iOS Autolayout和UIToolbar/UIBarButtonItems

out*_*orm 23 uitoolbar uibarbuttonitem ios autoresizingmask autolayout

我已经启用了自动布局在iOS视图,并有UIToolbar一个UISearchBarUISegmentControl载带的工具栏.我想要UISearchBar有一个灵活的宽度,所以我需要添加一个约束来强制这个,但从我可以告诉你不能添加约束到UIToolbar接口生成器中的项目.所有选项均已禁用.

AutoLayout我完成这个之前autoresizingmasks.

是否允许约束UIToolbars/UINavigationBars

使用autolayout时如何才能实现这一目标?

sno*_*ock 26

Autolayout约束仅适用于UIViews及其子类.

虽然UIToolbar允许一些UIView基础项目(例如UISearchBarUISegmentedControl),但它们可能必须共存UIBarButtonItems而不继承UIView.

在自动布局可以使用之前UIBarButtonItems,请按照您的操作进行操作.

您可以选择仅使用小部件来滚动自己的工具栏UIViews.

  • 知道Apple是否正在努力解决这个问题?如果我不得不在不同的地方使用AL和旧方法,那就会破坏我的不一致性. (4认同)

Nyc*_*cen 9

这也可以直接从故事板中完成.

只需拖放工具栏中的项目,然后将其中的一些项目转换为灵活或固定的空间即可获得所需的效果.请参阅以下两个示例.

均匀分布的

中心

注意:这是我对齐UIToolBar项目答案的副本,我在寻找这样的解决方案时遇到了两个问题


Ben*_*ger 7

你至少可以在代码中执行此操作; 我是抛弃Interface Builder的类型,无论如何都要用代码.在添加或调整约束时,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;
}
Run Code Online (Sandbox Code Playgroud)

因为我喜欢尽可能地延迟加载,所以这是我的self.label实例变量(在[self addSubview:self.label]上面获取消息时调用).

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

似乎为我工作.UIBarButtonItems不过,我不会添加任何内容,因此您的里程数会有所不同.