我有一个UISearchBar,我在其中得到了UITextfield,然后我想设置选定的文本范围,但是它总是返回零。这是我的密码:
UITextField *searchField = [self.searchBar valueForKey:@"_searchField"];
[searchField becomeFirstResponder]; // focus to this searchfield我填写了下面的文字:
self.searchBar.text = @"This is text";并检查UITextField文本是否已填写完毕。不过,有关UITextPosition和UITextRange的所有方法都返回零:
UITextRange *selectedRange = [searchField selectedTextRange]; //selectedRange = nil
UITextPosition *newPosition = [searchField positionFromPosition:selectedRange.start offset:addressToComplete.street.length]; //newPosition = nil
UITextRange *newRange = [searchField textRangeFromPosition:newPosition toPosition:newPosition]; //newRange = nil我的代码错了吗?
发布于 2015-05-20 05:14:49
你试过登录UITextField *searchField吗?从它的外观看它是零的。我想你的密码应该是..。
(UITextField *)[self.searchBar valueForKey:@"_searchField"]
(在尝试代码OooOoKayyy..。起作用了..。哈哈)顺便说一下,这就是我如何让UITextField在searchBar..。
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 .. >.< 我以编程的方式selectedTextRange(例如,目的),也许它与xibs自动收费表有关,或者其他什么东西(奇怪,我没有经历过),但它在那里,尝试它。:)
希望我帮了你..。
快乐编码..。干杯!
https://stackoverflow.com/questions/30339952
复制相似问题