我正在按照https://stackoverflow.com/a/14235624/855680上的答案设置我的动画UISearchBar
,它以较小的宽度开始,然后在活动时扩展到 iPhone 屏幕的整个宽度。它按预期展开,只是根本没有出现“取消”按钮。我已经尝试setShowsCancelButton:animated
同时调用searchBarTextDidBeginEditing:
and searchDisplayControllerWillBeginSearch:
,但无济于事。我错过了什么?这是我的代码:
HomeViewController.h
#import <UIKit/UIKit.h>
@interface HomeViewController : UIViewController <UISearchBarDelegate, UISearchDisplayDelegate>
@end
主视图控制器.m
#import "HomeViewController.h"
@interface HomeViewController ()
@property (strong, nonatomic) UISearchDisplayController *sdc;
@property (strong, nonatomic) UISearchBar *searchBar;
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Add dummy buttons to navigation bar.
UIBarButtonItem *btn1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:nil];
UIBarButtonItem *btn2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:nil];
[self.navigationItem setLeftBarButtonItems:@[btn1, btn2] animated:YES];
// Add UISearchBar.
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(100, 0, 150, 44)];
self.sdc = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.sdc.delegate = self;
[self.navigationController.navigationBar addSubview:self.searchBar];
}
// From this point onwards, pretty much copy-paste from the StackOverflow answer.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(adjustFrame:) name:UIKeyboardWillShowNotification object:nil];
[nc addObserver:self selector:@selector(adjustFrame:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[nc removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)adjustFrame:(NSNotification *) notification {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
[UIView setAnimationBeginsFromCurrentState:YES];
if ([[notification name] isEqual:UIKeyboardWillHideNotification]) {
// revert back to the normal state.
self.searchBar.frame = CGRectMake (100, 0, 150, 44);
}
else {
//resize search bar
self.searchBar.frame = CGRectMake (0,0,320,self.searchBar.frame.size.height);
}
[UIView commitAnimations];
}
// Try to catch the editing event and display the Cancel button.
// BOTH DON'T WORK.
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
[searchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {
[controller.searchBar setShowsCancelButton:YES animated:YES];
}
@end