How do you hide/show UISearchBar's scope bar with animation?

后端 未结 2 615
余生分开走
余生分开走 2021-02-12 22:52

I want to show no scope bar when the table is empty (before the search bar edits for the first time), no scope bar when it\'s editing, and finally show it when editing done. I k

相关标签:
2条回答
  • 2021-02-12 23:34

    Here's how to make the cancel button and the scope bar to be displayed only while editing.

    Complete code with the small bonus of animating the cancel button’s (dis)appearance:

    - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
        searchBar.showsScopeBar = YES;
        [searchBar sizeToFit];
        [searchBar setShowsCancelButton:YES animated:YES];
    
        return YES;
    }
    
    - (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
        searchBar.showsScopeBar = NO;
        [searchBar sizeToFit];
        [searchBar setShowsCancelButton:NO animated:YES];
    
        return YES;
    }
    

    EDIT - Version Swift 3

    public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        searchBar.showsScopeBar = true
        searchBar.sizeToFit()
        searchBar.setShowsCancelButton(true, animated: true)
    
        return true
    }
    
    public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
        searchBar.showsScopeBar = false
        searchBar.sizeToFit()
        searchBar.setShowsCancelButton(false, animated: true)
    
        return true
    }
    

    Source: http://www.alexandre-gomes.com/?p=418

    0 讨论(0)
  • 2021-02-12 23:40

    For the newer iOS versions (tested on 11-13), you don't have to implement any delegate methods for this to work.

    In iOS 13 the default behaviour is to always show the scope bar, even when search is not active. Previous iOS versions automatically show and hide the scope bar when search is active.

    You need to add this in viewDidLoad()

    if #available(iOS 13.0, *) {
        searchController.automaticallyShowsScopeBar = true
    }
    
    0 讨论(0)
提交回复
热议问题