2014-09-25 121 views
2

我有一個UITableView一個UISearchBar和我的實現如下:的UISearchBar失去焦點

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
    [self.searchBar becomeFirstResponder]; 
    if(searchText.length == 0) 
    { 
     self.isFiltered = NO;  
    } 
    else 
    { 
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.writer1 contains[c] %@", searchText]; 
     self.isFiltered = YES; 
     [[RTRepairOrderStore sharedStore] filterROArray:predicate]; 
    } 

    [self.tableView reloadData];  
} 

的問題是,當我鍵入一個字母在搜索欄中,搜索工作,但鍵盤被立即解僱。我怎樣才能防止這一點?

回答

0

When searchBar:textDidChange: called,searchBaris the FirstResponder。沒有必要發送一個becomeFirstResponder消息。
此外,您確實發送了becomeFirstResponderself.searchBar,這可能與在searchBar:textDidChange:方法調用期間轉移給您的searchBar不同。
我建議刪除[self.searchBar becomeFirstResponder];並檢查您的財產self.searchBar是否真的與回調searchBar:textDidChange:中的searchBar對象相關聯。

4

searchBar失去焦點,因爲它可能位於tableView標題中,並且tableView正在重新加載。

您可以通過防止這種情況:

  • 移動搜索欄所以它不再的tableView的子視圖。選項包括將searchBar放置在導航欄中,或放置在tableView上方的視圖中。

  • 用下列方法之一更換reloadData以避免重新加載的tableView頭:

    • 使用reloadSections:withRowAnimation:重新加載表的部分,或

    • 使用beginUpdatesendUpdates動畫更改要插入或刪除的特定行。

2

什麼工作對我來說是讓becomeFirstResponder呼叫reloadData一個後發生:

[self.tableView reloadData]; 
[self.searchBar becomeFirstResponder]; 

這是工作在iOS 8.1.2,我沒有對測試其他版本呢。

0

我遇到了上面遇到的相同問題,但是原因不同。我的UISearchBar位於表格頂部的一個單元內。打字時,我會打電話重新加載UITableView,這導致搜索欄失去焦點 - 因爲包含搜索欄的單元格是正在重新加載的單元格。

解決方案是隻重新加載我需要的細胞。我的搜索欄位於第0部分,所有搜索結果位於第1部分。因此,像這樣的調用確保只有第1部分被重新加載,並且搜索欄沒有失去焦點。

NSIndexSet *section1 = [NSIndexSet indexSetWithIndex:1]; 
[self.tableView reloadSections:section1 withRowAnimation:UITableViewRowAnimationAutomatic];