Заполните кнопки области действия для UISearchDisplayController? - PullRequest
0 голосов
/ 08 декабря 2011

Может кто-нибудь указать мне на документацию для кнопок области на UISearchDisplayController? Я просматриваю один из примеров Apple, TableSearch, и не вижу, как они заполняют панель области действия под UISearchBar. Панель области имеет

All, Device, Desktop, Portable

Я скопировал код из AppDelegate и MainViewController. Я не вижу, как эти кнопки области видимости заполнены.

В appDelegate я вижу, что они настраивают некоторые данные Product (Product имеет тип и имя, оба являются NSStrings),

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    // Create and configure the window, navigation controller, and main view controller.

    // Create the master list for the main view controller.
    NSArray *listContent = [[NSArray alloc] initWithObjects:
                         [Product productWithType:@"Device" name:@"iPhone"],
                         [Product productWithType:@"Device" name:@"iPod"],
                         [Product productWithType:@"Device" name:@"iPod touch"],
                         [Product productWithType:@"Desktop" name:@"iMac"],
                         [Product productWithType:@"Desktop" name:@"Mac Pro"],
                         [Product productWithType:@"Portable" name:@"iBook"],
                         [Product productWithType:@"Portable" name:@"MacBook"],
                         [Product productWithType:@"Portable" name:@"MacBook Pro"],
                         [Product productWithType:@"Portable" name:@"PowerBook"], nil];


    // Create and configure the main view controller.
    MainViewController *mainViewController = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
    mainViewController.listContent = listContent;
    [listContent release];

    // Add create and configure the navigation controller.
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController];
    self.navController = navigationController;
    [mainViewController release];
    [navigationController release];

    // Configure and display the window.
    [window addSubview:navController.view];
    [window makeKeyAndVisible];

Затем в своем классе MainViewController:

/*
     File: MainViewController.m 
 Abstract: Main table view controller for the application. 
  Version: 1.5 

 Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple 
 Inc. ("Apple") in consideration of your agreement to the following 
 terms, and your use, installation, modification or redistribution of 
 this Apple software constitutes acceptance of these terms.  If you do 
 not agree with these terms, please do not use, install, modify or 
 redistribute this Apple software. 

 In consideration of your agreement to abide by the following terms, and 
 subject to these terms, Apple grants you a personal, non-exclusive 
 license, under Apple's copyrights in this original Apple software (the 
 "Apple Software"), to use, reproduce, modify and redistribute the Apple 
 Software, with or without modifications, in source and/or binary forms; 
 provided that if you redistribute the Apple Software in its entirety and 
 without modifications, you must retain this notice and the following 
 text and disclaimers in all such redistributions of the Apple Software. 
 Neither the name, trademarks, service marks or logos of Apple Inc. may 
 be used to endorse or promote products derived from the Apple Software 
 without specific prior written permission from Apple.  Except as 
 expressly stated in this notice, no other rights or licenses, express or 
 implied, are granted by Apple herein, including but not limited to any 
 patent rights that may be infringed by your derivative works or by other 
 works in which the Apple Software may be incorporated. 

 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE 
 MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION 
 THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS 
 FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND 
 OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. 

 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL 
 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, 
 MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED 
 AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), 
 STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE 
 POSSIBILITY OF SUCH DAMAGE. 

 Copyright (C) 2010 Apple Inc. All Rights Reserved. 

 */

#import "MainViewController.h"
#import "Product.h"

@implementation MainViewController

@synthesize listContent, filteredListContent, savedSearchTerm, savedScopeButtonIndex, searchWasActive;


#pragma mark - 
#pragma mark Lifecycle methods

- (void)viewDidLoad
{
    self.title = @"Products";

    // create a filtered list that will contain products for the search results table.
    self.filteredListContent = [NSMutableArray arrayWithCapacity:[self.listContent count]];

    // restore search settings if they were saved in didReceiveMemoryWarning.
    if (self.savedSearchTerm)
    {
        [self.searchDisplayController setActive:self.searchWasActive];
        [self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
        [self.searchDisplayController.searchBar setText:savedSearchTerm];

        self.savedSearchTerm = nil;
    }

    [self.tableView reloadData];
    self.tableView.scrollEnabled = YES;
}

- (void)viewDidUnload
{
    self.filteredListContent = nil;
}

- (void)viewDidDisappear:(BOOL)animated
{
    // save the state of the search UI so that it can be restored if the view is re-created
    self.searchWasActive = [self.searchDisplayController isActive];
    self.savedSearchTerm = [self.searchDisplayController.searchBar text];
    self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
}

- (void)dealloc
{
    [listContent release];
    [filteredListContent release];

    [super dealloc];
}


#pragma mark -
#pragma mark UITableView data source and delegate methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    /*
     If the requesting table view is the search display controller's table view, return the count of
     the filtered list, otherwise return the count of the main list.
     */
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return [self.filteredListContent count];
    }
    else
    {
        return [self.listContent count];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *kCellID = @"cellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    /*
     If the requesting table view is the search display controller's table view, configure the cell using the filtered content, otherwise use the main list.
     */
    Product *product = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        product = [self.filteredListContent objectAtIndex:indexPath.row];
    }
    else
    {
        product = [self.listContent objectAtIndex:indexPath.row];
    }

    cell.textLabel.text = product.name;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIViewController *detailsViewController = [[UIViewController alloc] init];

    /*
     If the requesting table view is the search display controller's table view, configure the next view controller using the filtered content, otherwise use the main list.
     */
    Product *product = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        product = [self.filteredListContent objectAtIndex:indexPath.row];
    }
    else
    {
        product = [self.listContent objectAtIndex:indexPath.row];
    }
    detailsViewController.title = product.name;

    [[self navigationController] pushViewController:detailsViewController animated:YES];
    [detailsViewController release];
}


#pragma mark -
#pragma mark Content Filtering

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    /*
     Update the filtered array based on the search text and scope.
     */

    [self.filteredListContent removeAllObjects]; // First clear the filtered array.

    /*
     Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array.
     */
    for (Product *product in listContent)
    {
        if ([scope isEqualToString:@"All"] || [product.type isEqualToString:scope])
        {
            NSComparisonResult result = [product.name compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
            if (result == NSOrderedSame)
            {
                [self.filteredListContent addObject:product];
            }
        }
    }
}


#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString scope:
            [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];

    // Return YES to cause the search result table view to be reloaded.
    return YES;
}


- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
            [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];

    // Return YES to cause the search result table view to be reloaded.
    return YES;
}


@end

Ответы [ 2 ]

1 голос
/ 04 июня 2012

Откройте MainWindow.xib и выберите элемент управления SearBar.На панели утилит вы увидите заголовки панели областей.

1 голос
/ 08 декабря 2011

Вы можете установить массив строк, которые будут использоваться в качестве заголовка для каждой кнопки области. Они могут быть установлены в InterfaceBuilder или в коде следующим образом:

self.mainSearchBar.scopeButtonTitles = [NSArray arrayWithObjects:@"All", @"Device", @"Desktop", @"Portable", nil];

Вам также нужно установить для showScopeBar значение YES.

self.mainSearchBar.showsScopeBar = YES;
...