你试过记录UITextField *searchField
吗?从外观上看它为零..我认为您的代码应该是..
(UITextField *)[self.searchBar valueForKey:@"_searchField"]
([在尝试您的代码之后] OooOoKayyy .. 它有效.. 哈哈哈..)顺便说一句,这就是我在 searchBar 中获取 UITextField 的方式..
for (id object in [[[self.searchBar subviews] objectAtIndex:0] subviews])
{
if ([object isKindOfClass:[UITextField class]])
{
UITextField *searchField = (UITextField *)object;
break;
}
}
首先,我尝试了您所拥有的:
UITextField *searchField = (UITextField *)[searchBar valueForKey:@"_searchField"];
searchBar.text = @"This is text";
// and logging your searchField.text here.. returns nil/empty..
我试着像这样重新排列它......
searchBar.text = @"This is text";
UITextField *searchField = (UITextField *)[searchBar valueForKey:@"_searchField"];
NSLog(@"searchFields.text :%@", searchField.text);
我再次尝试了您的代码,-(void)viewDidLoad
但效果不佳,是的,正如您所说,它总是为零。现在看起来像这样..
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
searchBar.text = @"This is text"; // not important
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
[searchField becomeFirstResponder];
UITextRange *selectedRange = [searchField selectedTextRange]; //selectedRange = not nil anymore
NSLog(@"searchField.text :%@ -> selectedRange :%@\n\n" , searchField.text, selectedRange);
}
//i've also tried it inside uibutton's event and i worked .. >.<
我以编程方式选择了TextRange(例如出于目的),可能它与xibs自动布局或其他东西有关(奇怪的是我没有经历过)但它就在那里,试试吧.. :)
我希望我对你有所帮助..
快乐编码..干杯!