2011-12-08 61 views
6

有什麼方法可以選擇UISearchBar中的所有文本? 我試過[searchBar selectALL:],但它拋出了信號(無法識別的選擇器)。UISearchBar選擇所有文本

我想允許用戶更改以前的搜索文本。在某個時候,當用戶剛開始輸入新的請求時,應該解除舊的請求。如何實現它的標準方式 - 在文本開始編輯時選擇所有文本。

回答

2

這裏是另外一個建議:當有人啓動了搜索欄,有兩種可能的意圖:鍵入新文本或添加到現有的文本。我認爲你應該給你的用戶選擇。

如果他想添加文本,他自然會在現有文本的末尾再次點擊。

如果他想重新開始,他可以按搜索欄變爲活動時自動出現的清除按鈕。

+0

那麼,這是最好的解決方案。 –

+5

雖然此行爲與iOS上的Safari不同,但點擊地址欄時會選擇文本。 – Luke

0

我不認爲有一種方法可以選擇所有文本。也許當有一家專注於UISearchBar可以清除像這樣的搜索欄 - searchBar.text = @""

即在搜索欄明文......希望這有助於以某種方式...

+0

在這種情況下,有沒有辦法用戶變更請求。如果它是一個很長的字符串,那麼重新輸入它會很麻煩。 –

0

你可以做到這一點保持BOOL指示是否剛剛開始編輯搜索欄文本字段。然後,您可以在searchBar委託方法中捕獲第一個按鍵。

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

- (BOOL)searchBar:(UISearchBar *)searchBar 
     shouldChangeTextInRange:(NSRange)range 
     replacementText:(NSString *)text { 

    if (firstEdit) { 
     searchBar.text = text; 
     firstEdit = NO; 
    } 
    return YES; 
} 
+0

有什麼方法可以突出顯示文本嗎? –

4

如果您希望選擇UITextField中的文字(即十字上額外的水龍頭是不可接受的),您可以挖掘UISearchBar的子視圖以找到UITextField(或UISearchBarTextField),並選擇其中的文本:

// need to select the searchBar text ... 
UITextField * searchText = nil; 
for (UIView *subview in searchBar.subviews) 
{ 
    // we can't check if it is a UITextField because it is a UISearchBarTextField. 
    // Instead we check if the view conforms to UITextInput protocol. This finds 
    // the view we are after. 
    if ([subview conformsToProtocol:@protocol(UITextInput)]) 
    { 
     searchText = (UITextField*)subview; 
     break; 
    } 
} 

if (searchText != nil) 
    [searchText selectAll:self]; 
+2

請注意,這不再適用於iOS 7 - 文本字段現在在視圖層次結構中嵌套更深。要解決此問題,只需將代碼更改爲遍歷層次結構的遞歸版本,直到找到文本字段。根據你實際想要達到什麼,「selectAll:」方法也可能存在問題。 [看到這個問題的更多細節](http://stackoverflow.com/questions/1689911/programatically-select-all-text-in-uitextfield)。另外請注意,我必須在viewDidAppear中調用它,而不是viewWillAppear。 –

9

這可以通過使用標準的UIResponder語義來完成。無需深入研究UISearchBar的私有視圖層次結構。

[[UIApplication sharedApplication] sendAction:@selector(selectAll:) to:nil from:nil forEvent:nil] 

您可以從任何地方調用該方法,並selectAll:選擇將運行響應鏈,看看是否有物體迴應。假設您的搜索欄目前是第一個響應者(如果用戶輸入的話),它會響應並且結果將被選中。如果不是,您可以通過在搜索欄上撥打becomeFirstResponder來使其成爲第一響應者。

[_mySearchBar becomeFirstResponder] 
[[UIApplication sharedApplication] sendAction:@selector(selectAll:) to:nil from:nil forEvent:nil] 
2

在我的情況下,發送selectAll(_:)沒有立即調用becomeFirstResponder後工作。

我工作圍繞它通過等待一個runloop:

斯威夫特2:

dispatch_async(dispatch_get_main_queue()) { 
    UIApplication.sharedApplication().sendAction(#selector(UITextField.selectAll(_:)), to: nil, from: nil, forEvent: nil) 
} 

斯威夫特3:

DispatchQueue.main.async(execute: { 
    UIApplication.sharedApplication().sendAction(#selector(UITextField.selectAll(_:)), to: nil, from: nil, forEvent: nil) 
})