selectedTextRange在UISearchbar iOS中返回nil

时间:2015-05-20 03:51:04

标签: ios objective-c uitextfield uisearchbar uitextinput

我有一个UISearchBar,我得到UITextfield然后我想设置所选的文字范围,但它总是返回nil。这是我的代码:

UITextField *searchField = [self.searchBar valueForKey:@"_searchField"];
[searchField becomeFirstResponder]; // focus to this searchfield

我填写文字:

self.searchBar.text = @"This is text";

并检查是否填写了UITextField文本。尽管如此,关于UITextPositionUITextRange的所有方法都返回nil:

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

我的代码错了什么?

1 个答案:

答案 0 :(得分:0)

您是否尝试过记录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 autolayout或其他东西有关(奇怪的是我没有经历过)但是它就是,试试吧.. :)

我希望我帮助过你..

快乐的编码..干杯!