2011-10-27 10 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

のviewDidLoadでこのコードをキーボードを辞任すべきである。.. '[tempTextField setDelegate:自己];' – DefenestrationDay

+0

@DefenestrationDayあなたの答えは正しいです! – Shinigamae

答えて

0

があなたのヘッダにUITextFieldDelegateを追加し、このデリゲートメソッドを実装します:

textFieldShouldEndEditing: 

方法であなたの最初の応答者を辞任します。

3

あなたが欠けているのはUITextFieldDelegateです。これはさまざまな理由で呼び出される多くのテキストフィールドメソッドがあります。

アップルのドキュメントをチェックしてください! http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html

あなたは

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

使用中のあなたは、デリゲートを設定しなかった

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

- (void) hideKeyboard 
    { 
[textfieldname1 resignFirstResponder]; 
    [textfieldname2 resignFirstResponder]; 
    } 
関連する問題