无法解雇键盘

时间:2012-02-02 13:35:40

标签: objective-c ios uitextfield

我无法弄清楚如何触摸Done或文本字段之外的东西时解除键盘。这是我尝试的

myController.h

@interface myController : UIViewController <UITextFieldDelegate>{
    secondViewController *secondView;
}

myController.m

-(void)loadView
{
    .....
    textFieldRounded.borderStyle = UITextBorderStyleRoundedRect;
    textFieldRounded.textColor = [UIColor blackColor]; 
    textFieldRounded.font = [UIFont systemFontOfSize:17.0];
    textFieldRounded.placeholder = @"<enter text>";  
    textFieldRounded.backgroundColor = [UIColor whiteColor]; 
    textFieldRounded.autocorrectionType = UITextAutocorrectionTypeNo;    
    textFieldRounded.keyboardType = UIKeyboardTypeDefault;  
    textFieldRounded.returnKeyType = UIReturnKeyDone;  
    textFieldRounded.clearButtonMode = UITextFieldViewModeWhileEditing;    
    [textFieldRounded.delegate = self;        
    [self.view addSubview:textFieldRounded];

    ....
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return [textField resignFirstResponder];
}

2 个答案:

答案 0 :(得分:1)

使用:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

在文本区域外触摸时捕获

答案 1 :(得分:0)

要通过点击外部文本字段隐藏键盘,您可以使用如下所示的手势识别器

- (void)viewDidLoad
{
  // don't forget to assign textField delegate, after textField is created
  textFieldRounded.delegate = self;

  //...
  UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
  tapRecognizer.numberOfTouchesRequired = 1;
  [self.view addGestureRecognizer:tapRecognizer];
  [tapRecognizer release]
}

- (void)singleTap:(id)sender
{
  // if you have multiple text fields use this line:
  [self.view endEditing:NO];
}

// remove resigning call from textField delegate
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return YES;
}

// on Done/Return button handling use this
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
   [textField resignFirstResponder];
   return YES;
}