iOS隱藏鍵盤代碼


iOS隱藏鍵盤代碼

 

在View的UITextField中經常需要輸入完文字后隱藏軟鍵盤,要實現着一點要讓View的Controller實現UITextFieldDelegate代理,然后編寫相應的代碼。

 

  1. #import <UIKit/UIKit.h>
  2. @interface TestVeiwController : UIViewController<UITextFieldDelegate> {
  3. IBOutlet UITextField *txt;
  4. }
  5. @property (nonatomic,retain) UITextField *txt;
  6. @end

然后記得要指定文本框的代理

  1. - (void)viewDidLoad {
  2. [super viewDidLoad];
  3. txt.delegate = self;
  4. }

點擊Enter的時候隱藏軟鍵盤:

 

  1. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  2. {
  3. [textField resignFirstResponder];
  4. return YES;
  5. }



點擊取消(Cancel)或那個小差號的時候隱藏。注意這里如return YES則無法隱藏,我采用了點變通的方法。

  1. - (BOOL)textFieldShouldClear:(UITextField *)textField
  2. {
  3. [textField resignFirstResponder];
  4. textField.text = @”";
  5. return NO;
  6. }

點擊View的其他區域隱藏軟鍵盤。

  1. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  2. {
  3. [txt resignFirstResponder];
  4. }

這里直接用了我自定義的變量。

設置代理的步驟比較重要,別忘記了,要不沒反應

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM