简体   繁体   English

iOS 6-响应键盘完成按钮状态

[英]iOS 6 - Responding to Keyboard Done Button State

In the iOS Apprentice Series eBooks, you are supposed to build a Checklist app. 在iOS Apprentice系列电子书中,您应该构建一个清单应用程序。 The tutorials have you go through and make a Done button on a button bar that is disabled and enabled based on the text inside of a UITextField object. 本教程将指导您完成并根据UITextField对象内部的文本在按钮栏上创建“完成”按钮。

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range     replacementString:(NSString *)string
{
NSString *newText = [theTextField.text stringByReplacingCharactersInRange:range withString:string];

self.doneBarButton.enabled = ([newText length] > 0);

return YES;
}

Now, the keyboard is set to disable the Done button (on the keyboard) if the text field is empty. 现在,如果文本字段为空,则将键盘设置为禁用“完成”按钮(在键盘上)。 Is there a way to observe the state of the keyboard done button and have the done button bar button reflect it accordingly? 有没有办法观察键盘“完成”按钮的状态并使“完成”按钮栏按钮相应地反映出来?

IE, when the keyboard done button is enabled, the button bar done button is enabled. IE,当启用键盘完成按钮时,按钮栏完成按钮被启用。

UITextField supports what you want through the enablesReturnKeyAutomatically property. UITextField通过enablesReturnKeyAutomatically属性支持所需的内容。 This property is from the UITextInputTraits protocol. 此属性来自UITextInputTraits协议。

When you create your UITextField , set this property. 创建UITextField ,请设置此属性。

self.textField.enablesReturnKeyAutomatically = YES;

This means the Return key (whatever it is labeled) will automatically becomes disabled if the text field is empty. 这意味着如果文本字段为空,则“返回”键(无论是否带有标签)将自动被禁用。 And it automatically becomes enabled when text is entered. 输入文本后,它将自动启用。

There is no way to observe the state of this so you must implement the code you already have for textField:shouldChangeCharactersInRange:replacementString: to update your other Done button. 无法观察到这种状态,因此您必须实现textField:shouldChangeCharactersInRange:replacementString:已有的代码,以更新其他“完成”按钮。

You may add a target on your text field with the following events. 您可以在文本字段中添加带有以下事件的目标。

UIControlEventEditingDidBegin    
UIControlEventEditingChanged     
UIControlEventEditingDidEnd      
UIControlEventEditingDidEndOnExit
UIControlEventAllEditingEvents

Example: In viewDidLoad 示例:在viewDidLoad

[_textField addTarget:self action:@selector(textFieldEditing:) forControlEvents:UIControlEventAllEditingEvents];

Action Method: 动作方法:

- (void)textFieldEditing:(id)sender
{
    _doneButton.enable = ([[sender text] length]>0);
}

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

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