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

时间:2012-02-09 06:25:01

标签: iphone objective-c xcode ipad uitextfield

我正在开发一个iphone应用程序,只要在textfield中输入一个字符,我就必须返回键盘。如何实现这一点请提出一些解决方案。

感谢。

5 个答案:

答案 0 :(得分:4)

步骤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];

答案 1 :(得分:1)

你必须用

的文本委托方法编写代码
- (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];
}

}

答案 2 :(得分:0)

在textField创建代码

中添加通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeText:) name:UITextFieldTextDidChangeNotification object:textField];

并实施

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

答案 3 :(得分:0)

我想这是你想要的吗?

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

}

或者,如果您希望它在开始编辑后立即辞职,您可以将此代码放入textFieldDidBeginEditing:委托方法

[textField resignFirstResponder];

检查此链接

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

答案 4 :(得分:0)

- (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
   }

}