0

大家好,我已经编写了以下代码来实现搜索栏并且工作正常

    - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
 return YES;
}// return NO to not become first responder

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
 isSearchOn=YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
 searchBar.text=@"";
 isSearchOn=NO;
 [searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
 if ([searchText length]>0) 
  isSearchOn=YES;
 else
  isSearchOn=NO;

 NSLog(@"search text %@",searchText);
 [self searchText:searchText];
 [table reloadData];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
 isSearchOn=NO;
 [searchBar resignFirstResponder];
}


-(void)searchText:(NSString*)str
{
 NSLog(@"search text");
 [resultArray removeAllObjects];


 if (segmentControl.selectedSegmentIndex==0) {
  for (NSDictionary *CellDix in FriendSuggestion) 
  {
   NSRange titleResultRange =  [[CellDix valueForKey:@"itemid.item"] rangeOfString:str options: (NSCaseInsensitiveSearch | NSLiteralSearch)];

   NSRange titleRangePopular=[[CellDix valueForKey:@"usagecategoryid.usagecategory"] rangeOfString:str options:(NSCaseInsensitiveSearch | NSLiteralSearch)];

   if (titleResultRange.length > 0 || titleRangePopular.length>0)
    [resultArray addObject:CellDix];
  }
 }else
 {
  for (NSDictionary *CellDix in popularSuggestion) 
  {
   NSRange titleResultRange =  [[CellDix valueForKey:@"itemid.item"] rangeOfString:str options: (NSCaseInsensitiveSearch | NSLiteralSearch)];

   NSRange titleRangePopular=[[CellDix valueForKey:@"usagecategoryid.usagecategory"] rangeOfString:str options:(NSCaseInsensitiveSearch | NSLiteralSearch)];

   if (titleResultRange.length > 0 || titleRangePopular.length>0)
    [resultArray addObject:CellDix];
  }
 }


 NSLog(@"cellDics  array  %@",resultArray);
}

但是我遇到的问题是,当我在搜索栏上搜索文本然后单击搜索然后单击搜索栏文本右侧的十字按钮然后应用程序崩溃任何人都知道如何删除此问题。谢谢..

4

2 回答 2

0
Add one more delegate method.

    - (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
    {
     searchBar.text=@"";
    }

it is not genuine but from this your problem will be solved.
于 2012-05-31T15:20:06.250 回答
0

您应该检查搜索栏是否是“textDidChange:”方法中的第一响应者。

目标 C

 -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if ([searchText isFirstResponder]) {
      // do whatever you need to do
    }
}

迅速

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        if searchBar.isFirstResponder() {
          // do whatever you need to do
        }
}
于 2015-06-05T14:48:08.870 回答