iOS 7 doesn't show cancel button of search bar in navigation bar

后端 未结 8 1227
情书的邮戳
情书的邮戳 2021-02-04 02:47

In an app that\'s supposed to run on iOS 6 and iOS 7, the cancel button of the search bar embedded in the navigation bar is not shown anymore if the app is run on iOS 7. On iOS

8条回答
  •  失恋的感觉
    2021-02-04 03:24

    In my opinion this is a bug. Heres my workaround. It's not perfect but it works both on iOS 6&7. On iOS7 the searchbar textfield slides over the cancel button while it's fading out and on iOS6 the textfield width expansion isn't animated.

    @interface FTViewController ()
    @property(nonatomic, strong) UISearchBar *searchBar;
    @end
    
    @implementation FTViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        self.searchBar = [[UISearchBar alloc] init];
        self.searchBar.delegate = self;
    
        if (NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_6_1) {
            // iOS 6.1 and older (only tested on 6.1)
            [self.searchBar sizeToFit];
            self.searchBar.backgroundImage = nil;
        }
    
        self.navigationItem.titleView = self.searchBar;
    }
    
    -(void)cancelBarButtonItemClicked:(id)sender
    {
        [self searchBarCancelButtonClicked:self.searchBar];
    }
    
    -(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
    {
        [searchBar resignFirstResponder];
        [self.navigationItem setRightBarButtonItem:nil animated:YES];
    }
    
    -(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
    {
        UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelBarButtonItemClicked:)];
        [self.navigationItem setRightBarButtonItem:cancelBtn animated:YES];
    
        return YES;
    }
    @end
    

提交回复
热议问题