简体   繁体   English

使UITextField为第一响应者

[英]Make UITextField first responder

In a unit test I am trying to call becomeFirstResponder method on a UITextField, but I am getting NO ie its not becoming the first responder. 在单元测试中,我试图在UITextField上调用beginFirstResponder方法,但是我却没有获得响应,即它没有成为第一响应者。

The code looks as below: 代码如下:

UITextField *textField = [self.controller.searchBar valueForKey: @"_searchField"];
//    textField = [[UITextField alloc] initWithFrame:CGRectMake(10.0, 10.0, 400.0, 44.0)];
[self.navigationController.navigationBar addSubview:textField];

textField.enabled = YES;
STAssertTrue([textField becomeFirstResponder],
             @"TextField should be a first responder.");

Am I missing something here? 我在这里想念什么吗?

You are grabbing the value of the search bar for the textfield: 您正在获取文本字段搜索栏的值:

UITextField *textField = [self.controller.searchBar valueForKey: @"_searchField"];

But then you just ignore that value, and overwrite it with this: 但是然后您只需忽略该值,并使用以下值覆盖它:

textField = [[UITextField alloc] initWithFrame:CGRectMake(10.0, 10.0, 400.0, 44.0)];

You haven't added this new textField to any view and its just a lone textfield that is allocated and nothing more. 您尚未将此新的textField添加到任何视图中,而只是将其分配给了一个单独的textfield,仅此而已。 It can't be a first responder because its not part of an app. 它不能成为第一响应者,因为它不是应用程序的一部分。

There are better ways of getting access to the searchbar. 有更好的方法来访问搜索栏。

You can change the location of the search items with calls like searchTextPositionAdjustment and searchFieldBackgroundPositionAdjustment. 您可以使用searchTextPositionAdjustment和searchFieldBackgroundPositionAdjustment之类的调用来更改搜索项的位置。 And you can use the UISearchBarDelegate to get information on the text being entered. 您可以使用UISearchBarDelegate来获取有关正在输入的文本的信息。

How will it become first responder just because you got a reference to it? 仅仅因为您获得了对它的引用,它将如何成为第一响应者? Perhaps you meant to use isFirstResponder (it is already the first responder) or canBecomeFirstResponder (it can become the first responder). 也许您打算使用isFirstResponder(它已经是第一响应者)或canBecomeFirstResponder(它可以成为第一响应者)。

Otherwise, you need to set an NSNotification on UITextFieldTextDidBeginEditingNotification to get notified when it begins editing. 否则,您需要在UITextFieldTextDidBeginEditingNotification上设置NSNotification以便在开始编辑时得到通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM