在文本字段中输入一个字符时返回键盘



我正在开发一个iphone应用程序,在该应用程序中,只要在文本字段中键入一个字符,我就必须返回键盘。如何做到这一点,请提出一些解决方案。

谢谢。

步骤1:创建一个实现协议UITextFieldDelegate 的类

@interface TheDelegateClass : NSObject <UITextFieldDelegate>

步骤2:在实现中,重写方法-(BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // newString is what the user is trying to input.
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([newString length] < 1) {
        // If newString is blank we will just ingore it.
        return YES;
    } else
    {
        // Otherwise we cut the length of newString to 1 (if needed) and set it to the textField.
        textField.text = [newString length] > 1 ? [newString substringToIndex:1] : newString;
        // And make the keyboard disappear.
        [textField resignFirstResponder];
        // Return NO to not change text again as we've already changed it.
        return NO;
    }
}

步骤3:将委托类的一个实例设置为UITextField的委托。

TheDelegateClass *theDelegate = [[TheDelegateClass alloc] init];
[theTextField setDelegate:theDelegate];

您必须用的文本委托方法编写代码

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   if([textField.text length] == 1){
    [textField resignFirstResponder];
}

然后在textFieldDidBeginEditing 中检查您的字符串长度

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if([textField.text length] == 1){
    [textField resignFirstResponder];
}
}

在text中添加通知创建代码的字段

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeText:) name:UITextFieldTextDidChangeNotification object:textField];

并实现

- (void) changeText: (id) sender;
{
    if ([textField.text length] == 1) 
    {
        [textField resignFirstResponder];
    }        
}

我想这就是你想要的?

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{
   [textField resignFirstResponder];
   [add your method here];
    return YES;
}

或者,如果你想让它一开始编辑就辞职,你可以把这段代码放在textFieldDidBeginEdition:委托方法中

[textField resignFirstResponder];

检查这个链接

https://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   if([textField.text length] == 1){
       [textField resignFirstResponder];
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
   if([textField.text length]==1)
   {
       // here perform the action you want to do
   }
}

最新更新