有什么方法可以选择UISearchBar中的所有文本? 我试过[searchBar selectALL:],但它抛出了信号(无法识别的选择器)。UISearchBar选择所有文本
我想允许用户更改以前的搜索文本。在某个时候,当用户刚开始输入新的请求时,应该解除旧的请求。如何实现它的标准方式 - 在文本开始编辑时选择所有文本。
有什么方法可以选择UISearchBar中的所有文本? 我试过[searchBar selectALL:],但它抛出了信号(无法识别的选择器)。UISearchBar选择所有文本
我想允许用户更改以前的搜索文本。在某个时候,当用户刚开始输入新的请求时,应该解除旧的请求。如何实现它的标准方式 - 在文本开始编辑时选择所有文本。
这里是另外一个建议:当有人启动了搜索栏,有两种可能的意图:键入新文本或添加到现有的文本。我认为你应该给你的用户选择。
如果他想添加文本,他自然会在现有文本的末尾再次点击。
如果他想重新开始,他可以按搜索栏变为活动时自动出现的清除按钮。
我不认为有一种方法可以选择所有文本。也许当有一家专注于UISearchBar
可以清除像这样的搜索栏 - searchBar.text = @""
即在搜索栏明文......希望这有助于以某种方式...
在这种情况下,有没有办法用户变更请求。如果它是一个很长的字符串,那么重新输入它会很麻烦。 –
你可以做到这一点保持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;
}
有什么方法可以突出显示文本吗? –
如果您希望选择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];
请注意,这不再适用于iOS 7 - 文本字段现在在视图层次结构中嵌套更深。要解决此问题,只需将代码更改为遍历层次结构的递归版本,直到找到文本字段。根据你实际想要达到什么,“selectAll:”方法也可能存在问题。 [看到这个问题的更多细节](http://stackoverflow.com/questions/1689911/programatically-select-all-text-in-uitextfield)。另外请注意,我必须在viewDidAppear中调用它,而不是viewWillAppear。 –
这可以通过使用标准的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]
在我的情况下,发送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)
})
那么,这是最好的解决方案。 –
虽然此行为与iOS上的Safari不同,但点击地址栏时会选择文本。 – Luke