2011-10-27 49 views
0

我知道如何通過Interface Builder使用以下方法。以編程方式關閉TextField的鍵盤

-(void)dismissKeyboard 
{ 
    [testTextField resignFirstResponder]; 
} 

這樣,當我觸摸鍵盤外的區域或點擊「返回」時,鍵盤就會關閉。

但我不知道如何通過代碼完成。請教我,謝謝。

這裏的.H

#import <UIKit/UIKit.h> 

@interface SecondViewController : UIViewController 
{ 
    UITextField *testTextField; 
} 

@property (nonatomic,retain) UITextField *testTextField; 
@end 

這裏.M

#import "SecondViewController.h" 
@implementation SecondViewController 
@synthesize testTextField; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad];  

    UITextField *tempTextField = [[UITextField alloc] init]; 
    self.testTextField = tempTextField; 
    testTextField.frame = CGRectMake(100, 150, 200, 30); 
    testTextField.placeholder = @"Test"; 
    testTextField.backgroundColor = [UIColor whiteColor]; 
    testTextField.textColor = [UIColor blackColor]; 
    [self.view addSubview:testTextField]; 

} 
+0

您沒有設置委託.. '[tempTextField setDelegate:自我]' – DefenestrationDay

+0

@DefenestrationDay你的答案是正確的! – Shinigamae

回答

0

添加UITextFieldDelegate到你的頭和實現這個委託方法:

textFieldShouldEndEditing: 

辭職的第一響應者的方法。

3

使用viewDidLoad中這段代碼

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)]; 
[self.view addGestureRecognizer:gestureRecognizer]; 
    } 

- (void) hideKeyboard 
    { 
[textfieldname1 resignFirstResponder]; 
    [textfieldname2 resignFirstResponder]; 
    }