iOS 搜索栏不显示结果

Posted

技术标签:

【中文标题】iOS 搜索栏不显示结果【英文标题】:iOS search bar not showing results 【发布时间】:2014-05-28 19:41:29 【问题描述】:

*更新:这确实有效,我的自定义单元格的样式没有出现,因此单元格看起来是空白的。那么如何让searchResultsTableView 使用我的自定义单元格?

我在表格视图中实现了一个搜索栏。调试时搜索,过滤所有工作,但是当我在搜索栏中输入字符时,结果不会加载或显示。这就是我正在做的一切:

@interface InviteTableViewController ()<UIAlertViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate>

@property(nonatomic, strong) NSNumber *contactsCount;
@property(nonatomic, strong) InviteTableViewCell *selectedCell;

@property(strong, nonatomic) NSMutableArray *filteredContactArray;
@property (weak, nonatomic) IBOutlet UISearchBar *contactsSearchBar;
@end

@implementation InviteTableViewController

- (id)initWithStyle:(UITableViewStyle)style

    self = [super initWithStyle:style];
    if (self) 
        // Custom initialization
    
    return self;


- (void) extractAllContacts: (ABAddressBookRef) addressBookRef
    NSMutableArray *contactsArray = [NSMutableArray array];
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBookRef);

    for(int i = 0; i < numberOfPeople; i++)
        ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
        NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        if(firstName)
        ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);

        for (CFIndex i = 0; i < ABMultiValueGetCount(emails); i++) 
            NSString *email = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(emails, i);
            MyUser *amUser = [[MyUser alloc] init];
            amUser.email =email;

            NSString *fullName =[NSString stringWithFormat:@"%@ %@",firstName, (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty))];
            amUser.fullName = fullName;
            [contactsArray addObject:amUser];
        

        

    

    NSLog(@"================================count ============= %d", [contactsArray count]);
    contactsArray = [contactsArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) 
        NSDate *first = [(MyUser*) a fullName];
        NSDate *second = [(MyUser*)b fullName];
        return [first compare:second];
    ];
    self.inviteContactsArray = contactsArray;
    self.filteredContactArray = [NSMutableArray arrayWithCapacity:[contactsArray count]];

    [self.tableView reloadData];




- (void)viewDidLoad

    [super viewDidLoad];  

    _contactsCount = [NSNumber numberWithInt:0];


    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);

    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) 
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) 
            if (granted) 
                [self extractAllContacts: addressBookRef];
                [self.tableView reloadData];
             else 
                NSString *message = [NSString stringWithFormat:@"You have not given permission to use your address book.  Please allow in settings "];
                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Enable Contacts" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

                [alert show];
            
        );
    
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) 
        // The user has previously given access, add the contact
        [self extractAllContacts:addressBookRef];
    
    else 
        // The user has previously denied access
        // Send an alert telling user to change privacy setting in settings app
    

[self.tableView reloadData];


- (void)didReceiveMemoryWarning

    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

    // Return the number of sections.
    return 1;


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section


    if (tableView == self.searchDisplayController.searchResultsTableView) 
        return [self.filteredContactArray count];
     else 
        return [self.inviteContactsArray count];
    


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath



    static NSString *CellIdentifier = @"InviteCell";

    InviteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if ( cell == nil ) 
        cell = [[InviteTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    

    MyUser *person = nil;

    if (tableView == self.searchDisplayController.searchResultsTableView)
    

        person = [self.filteredContactArray objectAtIndex:[indexPath row]];
        NSMutableArray *tempArray = self.filteredContactArray;

    
    else
    
        person = [self.inviteContactsArray objectAtIndex:[indexPath row]];
    




    //InviteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    person = [self.inviteContactsArray objectAtIndex:indexPath.row];

    cell.nameLabel.text = person.fullName;
    cell.emailLabel.text = person.email;

    return cell;






#pragma mark Content Filtering
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope 


    // Update the filtered array based on the search text and scope.
    // Remove all objects from the filtered search array
    [self.filteredContactArray removeAllObjects];
    // Filter the array using NSPredicate
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.fullName contains[c] %@",searchText];
    self.filteredContactArray = [NSMutableArray arrayWithArray:[self.inviteContactsArray filteredArrayUsingPredicate:predicate]];




#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;



@end

这就是它的样子:

【问题讨论】:

【参考方案1】:

同意@rdelmar。

BUT TableView 中存在一种棘手的行为,如果你更改代码中的

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    ....
    InviteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    ....

InviteTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

如果添加了前缀“self”。您的代码应该可以正常工作。

if ( cell == nil )
 
    cell = [[InviteTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
 

是不必要的。它只会为您创建一个似乎不是您想要的标准“字幕单元”,只需将其删除即可。

【讨论】:

【参考方案2】:

如果您想对主表和搜索结果表使用相同的单元格,您应该在 xib 中创建单元格(或者您可以完全在代码中完成)。在 viewDidLoad 中,为两个表视图注册 nib,

- (void)viewDidLoad 
    [super viewDidLoad];
    [self.searchDisplayController.searchResultsTableView registerNib:[UINib nibWithNibName:@"InviteTableViewCell" bundle:nil] forCellReuseIdentifier:@"InviteCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"InviteTableViewCell" bundle:nil] forCellReuseIdentifier:@"inviteCell"];

在 cellForRowAtIndexPath 中,你可以这样做,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    InviteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InviteCell" forIndexPath:indexPath];
    MyUser *person = ([tableView isEqual:self.tableView])? self.inviteContactsArray[indexPath.row] : self.filteredContactArray[indexPath row];
    cell.nameLabel.text = person.fullName;
    cell.emailLabel.text = person.email;
    return cell;

如果您已经在情节提要中设置了单元格,则可以将其复制并粘贴到一个空的 xib 文件中,这样您就不必重新设置它。您可以从情节提要表格视图中删除单元格,因为您将从 xib 文件中获取单元格。

【讨论】:

【参考方案3】:

viewdidload 中的下一行应该可以解决问题

self.searchDisplayController.searchResultsTableView.rowHeight = self.tableView.rowHeight

【讨论】:

以上是关于iOS 搜索栏不显示结果的主要内容,如果未能解决你的问题,请参考以下文章

输入一个字母时,搜索栏不显示所有相关结果

搜索栏不返回任何结果

UITableView 中的搜索栏不显示单元格标签中的文本

IOS 7状态栏不显示? [复制]

iOS - 方向更改时导航栏不显示大标题

iOS:当从主视图控制器嵌入时,导航栏不显示