您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 開發:讓 UITextField 輸入完成後自動隱藏鍵盤

編輯:iOS 相關資訊

在使用 UITextField 時,往往需要在使用者輸入完成後隱藏軟鍵盤。要實現這一點,需要讓視圖的 Controller 遵循 UITextFieldDelegate 代理,並撰寫相應程式碼。

一、宣告並指定代理

首先在介面中宣告 UITextField,並讓類別遵循 UITextFieldDelegate 協議:

#import <UIKit/UIKit.h>

@interface TestViewController : UIViewController <UITextFieldDelegate>
{
    IBOutlet UITextField *txt;
}
@property (nonatomic, retain) UITextField *txt;
@end

接著別忘了在 viewDidLoad 中指定文本框的代理,這一步非常關鍵,否則後續方法不會有反應:

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

二、點擊 Enter 隱藏鍵盤

當使用者按下鍵盤的 Return 鍵時,透過 textFieldShouldReturn 方法讓文本框放棄第一響應者即可:

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

三、點擊清除按鈕時隱藏

當使用者點擊清除(那個小叉號)時也可一併隱藏鍵盤。此處若回傳 YES 反而無法隱藏,因此採取迂迴做法,回傳 NO 並清空文字:

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    [textField resignFirstResponder];
    textField.text = @"";
    return NO;
}

四、點擊視圖其他區域隱藏

若希望點擊視圖空白處時收起鍵盤,可重寫 touchesBegan 方法:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [txt resignFirstResponder];
}

總結來說,設定代理是最關鍵的一步,只要記得指定 delegate,再搭配上述幾個方法,就能靈活控制軟鍵盤的顯示與隱藏。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved