2

在 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。有没有办法处理这个?谢谢!

4

1 回答 1

0

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

于 2013-10-09T02:58:38.950 回答