我正在开发一个iPhone应用程序,我正在继承UINavigationBar来创建我的自定义导航栏 . 我想要的是一个更高的导航栏,以及一个位于titleView中的UISearchBar . 我想在导航栏中留出更多空间,因为我想在搜索栏下面的底部放置一个分段控件 . 这是我到目前为止所做的:
// Custom navigation bar implementation
const CGFloat BUNavigationBarHeightIncrease = 38.0f;
@implementation BUNavigationBar
// This resizes the navigation bar height
- (CGSize)sizeThatFits:(CGSize)size {
CGSize amendedSize = [super sizeThatFits:size];
amendedSize.height += BUNavigationBarHeightIncrease;
return amendedSize;
}
// This repositions the navigation buttons
- (void)layoutSubviews {
[super layoutSubviews];
NSArray *classNamesToReposition = @[@"UINavigationButton"];
for (UIView *view in [self subviews]) {
if ([classNamesToReposition containsObject:NSStringFromClass([view class])]) {
CGRect frame = [view frame];
frame.origin.y -= BUNavigationBarHeightIncrease;
[view setFrame:frame];
}
}
}
@end
我将此导航栏分配给导航控制器,如下所示:
- (IBAction)searchButton:(id)sender {
SearchViewController *searchViewController = [[SearchViewController alloc] init];
UINavigationController *searchNavigationController = [[UINavigationController alloc] initWithNavigationBarClass:[BUNavigationBar class] toolbarClass:nil];
[searchNavigationController setViewControllers:[NSArray arrayWithObjects:searchViewController, nil]];
[self presentViewController:searchNavigationController animated:YES completion:nil];
}
在SearchViewController的viewDidLoad中,我有这个:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.searchBar = [[UISearchBar alloc] init];
self.cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:@selector(cancelButton:)];
[self.searchBar setSearchBarStyle:UISearchBarStyleMinimal];
[self.searchBar setPlaceholder:@"Search"];
// For debugging purposes
[self.searchBar setBackgroundColor:[UIColor greenColor]];
[self.navigationItem setTitleView:self.searchBar];
[self.navigationItem setRightBarButtonItem:self.cancelButton];
}
以下是这之后屏幕的样子:Simulator screenshot
搜索栏位于中间,框架已拉伸以填充整个导航栏(以绿色显示) . 相反,我想要的是搜索栏保持默认高度,并移动到导航栏的顶部 . 我怎样才能做到这一点?
1 回答
只需在viewDidLoad中调用以下函数即可