1

我有一个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

我的代码有问题吗?

4

1 回答 1

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自动布局或其他东西有关(奇怪的是我没有经历过)但它就在那里,试试吧.. :)

我希望我对你有所帮助..

快乐编码..干杯!

于 2015-05-20T05:14:49.377 回答