单击搜索按钮后单击UISearchBar的十字按钮会使应用程序崩溃?

时间:2012-05-31 13:46:12

标签: iphone objective-c ios

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

    - (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);
}

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

2 个答案:

答案 0 :(得分:0)

Add one more delegate method.

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

it is not genuine but from this your problem will be solved.

答案 1 :(得分: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
        }
}