使用AutoLayout在UISearchBar的右侧添加一个按钮:“执行-layoutSubviews后仍需要自动布局”

时间:2013-07-29 03:01:19

标签: ios uibutton uisearchbar autolayout

在ios6上,我正在尝试执行以下操作:

UIButton *shortcutButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[shortcutButton setTitle:@"Shortcut" forState:UIControlStateNormal];
[shortcutButton addTarget:self action:@selector(createShortcut) forControlEvents:UIControlEventTouchUpInside];
[shortcutButton setFrame:CGRectMake(0, 0, 70, 20)];
[self.searchBar addSubview:shortcutButton];

[shortcutButton setTranslatesAutoresizingMaskIntoConstraints:NO];

NSMutableArray *searchBarConstraints = [NSMutableArray array];

[searchBarConstraints addObject: [NSLayoutConstraint constraintWithItem:self.searchBar
                                                              attribute:NSLayoutAttributeCenterY
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:shortcutButton
                                                              attribute:NSLayoutAttributeCenterY
                                                             multiplier:1
                                                               constant:0]];

[searchBarConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[shortcutButton]-35-|"
                                                                                  options:0
                                                                                  metrics:nil
                                                                                    views:@{ @"shortcutButton" : shortcutButton  ,  @"view" : self.view }]];
[self.searchBar addConstraints:searchBarConstraints];

这导致崩溃并出现错误:

*** Assertion failure in -[UISearchBar layoutSublayersOfLayer:], /SourceCache/UIKit/UIKit-2380.17/UIView.m:5776
Uncaught exception: Auto Layout still required after executing -layoutSubviews. UISearchBar's implementation of -layoutSubviews needs to call super.

我正在以编程方式创建UISearchbar并尝试在搜索栏的右侧插入UIButton。有办法处理这个吗?谢谢!

1 个答案:

答案 0 :(得分:0)

yahuuu我找到了解决方案。 尝试将设置约束逻辑放入didMoveToSuperview方法中。 我认为这与在加载层次结构上的所有视图之前设置约束有关。 或者只是调用[super layoutSubviews];设置约束后