UISearchController in a UIViewController

前端 未结 4 1953
无人共我
无人共我 2020-12-28 10:13

I\'m looking to create similar functionality to Apple\'s maps application in Swift. Is there anyway to integrate a UISearchController in to a regular view (i.e.: not a UITab

4条回答
  •  情深已故
    2020-12-28 10:35

    If you want to use UISearchController with a non UITableView, here is how I did it.

    Since the UISearchController is not (yet!) supported by IB, you do not need to add anything in it, like a UISearchBar.

    @interface UIViewControllerSubclass () 
    
    @property (strong, nonatomic) UISearchController *searchController;
    
    @end
    
    @implementation UIViewControllerSubclass
    
    - (void)viewDidLoad
    {        
        [super viewDidLoad];
        // Do any custom init from here...
    
        // Create a UITableViewController to present search results since the actual view controller is not a subclass of UITableViewController in this case
        UITableViewController *searchResultsController = [[UITableViewController alloc] init];
    
        // Init UISearchController with the search results controller
        self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
    
        // Link the search controller
        self.searchController.searchResultsUpdater = self;
    
        // This is obviously needed because the search bar will be contained in the navigation bar
        self.searchController.hidesNavigationBarDuringPresentation = NO;
    
        // Required (?) to set place a search bar in a navigation bar
        self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    
        // This is where you set the search bar in the navigation bar, instead of using table view's header ...
        self.navigationItem.titleView = self.searchController.searchBar;
    
        // To ensure search results controller is presented in the current view controller
        self.definesPresentationContext = YES;
    
        // Setting delegates and other stuff
        searchResultsController.tableView.dataSource = self;
        searchResultsController.tableView.delegate = self;
        self.searchController.delegate = self;
        self.searchController.dimsBackgroundDuringPresentation = NO;
        self.searchController.searchBar.delegate = self;        
    }
    
    @end
    

    I hope it is enough to work :-)

    Then of course you need at least to implement UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdater methods.

    Enjoy!

提交回复
热议问题