IOS 鍵盤監(jiān)聽實(shí)例

方便快捷的收鍵盤:

[[[UIApplicationsharedApplication]keyWindow]endEditing:YES];

//注冊(cè)鍵盤位置變化監(jiān)聽

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(setFrame:)name:UIKeyboardWillChangeFrameNotificationobject:nil];

-(void)setFrame:(NSNotification*)notification{

NSDictionary* inforDic = [notificationuserInfo];

//使用鍵盤的frame已經(jīng)變化完的key值信息

CGRectkbSize = [[inforDicobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

NSLog(@"y值%f",kbSize.origin.y);

floatDur = [[inforDicobjectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];

NSTimeIntervalanimationDuration = Dur;

[UIViewbeginAnimations:@"ResizeForKeyboard"context:nil];

[UIViewsetAnimationDuration:animationDuration];

if(kbSize.origin.y<400) {

self.xinxiView.frame=CGRectMake(10,15,self.xinxiView.frame.size.width,302);

}else{

self.xinxiView.frame=CGRectMake(10,69,self.xinxiView.frame.size.width,302);

}

[UIViewcommitAnimations];

}

一.鍵盤通知

當(dāng)文本View(如UITextField,UITextView,UIWebView內(nèi)的輸入框)進(jìn)入編輯模式成為first responder時(shí)僚焦,系統(tǒng)會(huì)自動(dòng)顯示鍵盤注盈。成為firstresponder可能由用戶點(diǎn)擊觸發(fā),也可向文本View發(fā)送becomeFirstResponder消息觸發(fā)巴元。當(dāng)文本視圖退出first responder時(shí)草雕,鍵盤會(huì)消失卿泽。文本View退出first responder可能由用戶點(diǎn)擊鍵盤上的Done或Return鍵結(jié)束輸入觸發(fā)奋救,也可向文本View發(fā)送resignFirstResponder消息觸發(fā)玫坛。

當(dāng)鍵盤顯示或消失時(shí)结笨,系統(tǒng)會(huì)發(fā)送相關(guān)的通知:UIKeyboardWillShowNotificationUIKeyboardDidShowNotificationUIKeyboardWillHideNotificationUIKeyboardDidHideNotification

通知消息NSNotification中的userInfo字典中包含鍵盤的位置和大小信息,對(duì)應(yīng)的key為

UIKeyboardFrameBeginUserInfoKeyUIKeyboardFrameEndUserInfoKeyUIKeyboardAnimationDurationUserInfoKeyUIKeyboardAnimationCurveUserInfoKey

UIKeyboardFrameBeginUserInfoKey,UIKeyboardFrameEndUserInfoKey對(duì)應(yīng)的Value是個(gè)NSValue對(duì)象湿镀,內(nèi)部包含CGRect結(jié)構(gòu)炕吸,分別為鍵盤起始時(shí)和終止時(shí)的位置信息。

UIKeyboardAnimationCurveUserInfoKey對(duì)應(yīng)的Value是NSNumber對(duì)象勉痴,內(nèi)部為UIViewAnimationCurve類型的數(shù)據(jù)赫模,表示鍵盤顯示或消失的動(dòng)畫類型。

UIKeyboardAnimationDurationUserInfoKey對(duì)應(yīng)的Value也是NSNumber對(duì)象蒸矛,內(nèi)部為double類型的數(shù)據(jù)瀑罗,表示鍵盤h顯示或消失時(shí)動(dòng)畫的持續(xù)時(shí)間。

例如莉钙,在UIKeyboardWillShowNotification廓脆,UIKeyboardDidShowNotification通知中的userInfo內(nèi)容為

userInfo = {

UIKeyboardAnimationCurveUserInfoKey = 0;

UIKeyboardAnimationDurationUserInfoKey = "0.25";

UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 216}}";

UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 588}";

UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 372}";

UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 216}}";

UIKeyboardFrameChangedByUserInteraction = 0;

UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 264}, {320, 216}}";

}

在UIKeyboardWillHideNotification,UIKeyboardDidHideNotification通知中的userInfo內(nèi)容為:

userInfo = {

UIKeyboardAnimationCurveUserInfoKey = 0;

UIKeyboardAnimationDurationUserInfoKey = "0.25";

UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 216}}";

UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 372}";

UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 588}";

UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 264}, {320, 216}}";

UIKeyboardFrameChangedByUserInteraction = 0;

UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 480}, {320, 216}}";

}

Text,Web, and Editing Programming Guide for iOS中,有如下描述Note: The rectangle contained in the UIKeyboardFrameBeginUserInfoKey and UIKeyboardFrameEndUserInfoKey properties of the userInfo dictionary should be used only for the size information it contains. Do not use the origin of the rectangle (which is always {0.0, 0.0}) in rectangle-intersection operations. Because the keyboard is animated into position, the actual bounding rectangle of the keyboard changes over time.但從實(shí)際獲取的信息來(lái)看磁玉,矩形的origin并不為{0.0, 0.0},這里應(yīng)該不準(zhǔn)確停忿。

二.文本對(duì)象與WebView鍵盤設(shè)置

UITextFiledUITextView都遵循UITextInputTraits協(xié)議,在UITextInputTraits協(xié)議中定義了設(shè)置鍵盤的屬性蚊伞,有

1.keyboardType:鍵盤類型席赂,如UIKeyboardTypeDefault,UIKeyboardTypeURL,UIKeyboardTypeEmailAddress,UIKeyboardTypePhonePad

2.returnKeyType:鍵盤Return鍵顯示的文本,默認(rèn)為”Return”,其他可選擇的包括Go,Next,Done,Send,Google等时迫。

3.keyboardAppearance:鍵盤外觀颅停,默認(rèn)為UIKeyboardAppearanceDefault,即上圖中的淺蘭色不透明背景掠拳,另外還有一種為UIKeyboardAppearanceAlert癞揉,鍵盤背景為黑色半透明,用于在警告框輸入時(shí)顯示溺欧,例如appStore中輸入密碼時(shí):

若想顯示黑色鍵盤又不想透明露出底部視圖喊熟,可以將鍵盤配置成Alert類型的,然后監(jiān)聽鍵盤顯示的廣播通知姐刁,在顯示鍵盤時(shí)在鍵盤底部增加一不透明黑色背景視圖芥牌。

注:在蘋果的鍵盤示例程序KeyboardAccessory中,將UITextView鍵盤類型更改為UIKeyboardAppearanceAlert,在iPad模擬器中運(yùn)行鍵盤并沒有出現(xiàn)黑色透明的效果聂使,不知為何? 在iPhone中UIKeyboardAppearanceAlert設(shè)置有效壁拉。

4.autocapitalizationType:文本大小寫樣式谬俄,見UITextAutocapitalizationType。5.autocorrectionType:是否自動(dòng)更正弃理,見UITextAutocorrectionType溃论。6.spellCheckingType:拼寫檢查設(shè)置,見UITextSpellCheckingType案铺。7.enablesReturnKeyAutomatically:是否在無(wú)文本時(shí)禁用Return鍵蔬芥,默認(rèn)為NO。若為YES,則用戶至少輸入一個(gè)字符后Return鍵才被激活控汉。?8.secureTextEntry:若輸入的是密碼笔诵,可設(shè)置此類型為YES,輸入字符時(shí)可顯示最后一個(gè)字符,其他字符顯示為點(diǎn)姑子。

UIWebView本身不直接遵循UITextInputTraits協(xié)議乎婿,但同樣可設(shè)置其內(nèi)部輸入部件的鍵盤屬性。如Configuring the Keyboard for Web Views中所述街佑。

設(shè)置autocorrect, auto-capitalization屬性谢翎。

設(shè)置鍵盤類型:

Text: Telephone: URL: Email: Zip code:

三. 使用鍵盤通知調(diào)整文本視圖位置

當(dāng)文本視圖成為First Responser時(shí)在窗口底部會(huì)顯示出鍵盤,顯示的鍵盤很可能會(huì)將文本視圖蓋住從而無(wú)法看到編輯的效果沐旨。鍵盤通知的一大用途即在鍵盤顯示或隱藏時(shí)獲取到鍵盤的位置信息森逮,從而可以調(diào)整窗口中的文本視圖位置或大小,使其可以在鍵盤上方顯示磁携。

Text, Web, and Editing Programming Guide for iOS中的MovingContent That Is Located Under the Keyboard節(jié)在鍵盤顯示和消失通知中褒侧,通過(guò)調(diào)整內(nèi)容UIScrollView視圖的contentInsetcontentOffset來(lái)保證編輯的文本視圖不會(huì)被鍵盤蓋住。

其流程為1.在初始化(viewDidLoadviewWillAppear)時(shí)谊迄,注冊(cè)處理鍵盤通知的方法闷供。

- (void)registerForKeyboardNotifications

{

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(keyboardWasShown:)

name:UIKeyboardDidShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(keyboardWillBeHidden:)

name:UIKeyboardWillHideNotification object:nil];

}

2.在鍵盤顯示的通知事件處理中獲取到即將顯示鍵盤的大小,將UIScrollViewcontentInset設(shè)置為鍵盤的frame區(qū)域统诺,同樣設(shè)置scrollIndicatorInsets保證滾動(dòng)條不會(huì)被鍵盤蓋住歪脏。獲取到編輯文本視圖的原點(diǎn)位置,與鍵盤顯示區(qū)域比較粮呢,若會(huì)被鍵盤覆蓋婿失,則調(diào)整contentOffset以使其在鍵盤上方

// Called when the UIKeyboardDidShowNotification is sent.

- (void)keyboardWasShown:(NSNotification*)aNotification

{

NSDictionary* info = [aNotification userInfo];

CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);

scrollView.contentInset = contentInsets;

scrollView.scrollIndicatorInsets = contentInsets;

// If active text field is hidden by keyboard, scroll it so it's visible

// Your application might not need or want this behavior.

CGRect aRect = self.view.frame;

aRect.size.height -= kbSize.height;

if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {

CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);

[scrollView setContentOffset:scrollPoint animated:YES];

}

}

3.在鍵盤消失的通知處理事件中,簡(jiǎn)單的將UIScrollView恢復(fù)即可

// Called when the UIKeyboardWillHideNotification is sent

- (void)keyboardWillBeHidden:(NSNotification*)aNotification

{

UIEdgeInsets contentInsets = UIEdgeInsetsZero;

scrollView.contentInset = contentInsets;

scrollView.scrollIndicatorInsets = contentInsets;

}

在蘋果的KeyboardAccessory示例程序中同樣演示了使用鍵盤通知來(lái)調(diào)整文本視圖位置的代碼啄寡,其中使用了鍵盤通知中的鍵盤動(dòng)畫時(shí)間豪硅,從而使文本視圖移動(dòng)的動(dòng)畫與鍵盤的顯示和消失同步。

- (void)keyboardWillShow:(NSNotification *)notification {

/*

Reduce the size of the text view so that it's not obscured by the keyboard.

Animate the resize so that it's in sync with the appearance of the keyboard.

*/

NSDictionary *userInfo = [notification userInfo];

// Get the origin of the keyboard when it's displayed.

NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

// Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.

CGRect keyboardRect = [aValue CGRectValue];

keyboardRect = [self.view convertRect:keyboardRect fromView:nil];

CGFloat keyboardTop = keyboardRect.origin.y;

CGRect newTextViewFrame = self.view.bounds;

newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;

// Get the duration of the animation.

NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

NSTimeInterval animationDuration;

[animationDurationValue getValue:&animationDuration];

// Animate the resize of the text view's frame in sync with the keyboard's appearance.

[UIView beginAnimations:nil context:NULL];

[UIView setAnimationDuration:animationDuration];

textView.frame = newTextViewFrame;

[UIView commitAnimations];

}

- (void)keyboardWillHide:(NSNotification *)notification {

NSDictionary* userInfo = [notification userInfo];

/*

Restore the size of the text view (fill self's view).

Animate the resize so that it's in sync with the disappearance of the keyboard.

*/

NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

NSTimeInterval animationDuration;

[animationDurationValue getValue:&animationDuration];

[UIView beginAnimations:nil context:NULL];

[UIView setAnimationDuration:animationDuration];

textView.frame = self.view.bounds;

[UIView commitAnimations];

}

關(guān)于調(diào)整文本視圖大小的代碼这难,還可以參考Different way to show keyboard and resize UIView with text field

還可以在鍵盤通知中實(shí)現(xiàn)自定義鍵盤葡秒,例如UIKEYBOARDTYPENUMBERPAD AND THE MISSING “RETURN” KEY中使用鍵盤通知在數(shù)字鍵盤中增加Return鍵,還可參考UIKeyboardTypeNumberPad鍵盤增加Return鍵

注:若在同一窗口中有兩個(gè)UITextField,當(dāng)?shù)谝粋€(gè)UITextField成為First Responser時(shí)姻乓,開始顯示鍵盤并接收到UIKeyboardWillShowNotification,UIKeyboardDidShowNotification通知,當(dāng)First Responser轉(zhuǎn)移到第二個(gè)UITextField時(shí)嵌溢,鍵盤會(huì)一直顯示,此時(shí)不會(huì)收到WillShow和DidShow的通知蹋岩。

四.使用inputAccessoryView與inputView定制輸入視圖

inputAccessoryViewinputView屬性在UIResponder中定義赖草,為readonly的屬性,但在UITextFiledUITextView中重新定義為了readwrite的屬性剪个,可以由用戶賦值秧骑。若inputView的不為nil,則當(dāng)文本視圖成為first responder時(shí),不會(huì)顯示系統(tǒng)鍵盤扣囊,而是顯示自定義的inputView;若inputAccessoryView不為nil,則inputAccessoryView會(huì)顯示在系統(tǒng)鍵盤或定制inputView的上方乎折。當(dāng)使用inputView時(shí),仍然會(huì)有WillShow,DidShow,WillHide,DidHide的鍵盤通知侵歇,通知中的BeginFrame與EndFrame為系統(tǒng)鍵盤(或inputView)與inputAccessoryView一起的frame骂澄。

自定義inputAccessoryView非常常見,如編輯短信時(shí)的輸入框Web頁(yè)面輸入鍵盤新浪微博評(píng)論界面

若想在輸入時(shí)不使用系統(tǒng)鍵盤,而使用自定義的鍵盤惕虑,則可以設(shè)置inputView坟冲,如隨手記中的金額輸入時(shí)的鍵盤若不想使用鍵盤輸入,想從UIPickerView或UIDatePicker中選擇溃蔫,可設(shè)置inputView為對(duì)應(yīng)的Picker視圖健提,如圖

蘋果鍵盤示例程序KeyboardAccessory演示了inputAccessoryView的使用方法。iOS,Want a “button” above a UIPicker or Keyboard, inputView,inputAccessoryView演示了在UIPickerView之上添加Toolbar的代碼伟叛。

在標(biāo)準(zhǔn)視圖中只有UITextField和UITextView將inputView和inputAccessoryView重新定義為了readwrite類型私痹,若想在自定義視圖中使用,需要在自定義視圖中重新定義inputView和inputAccessoryView屬性痪伦。見Input Views and Input Accessory Views侄榴。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市网沾,隨后出現(xiàn)的幾起案子癞蚕,更是在濱河造成了極大的恐慌,老刑警劉巖辉哥,帶你破解...
    沈念sama閱讀 216,402評(píng)論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件桦山,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡醋旦,警方通過(guò)查閱死者的電腦和手機(jī)恒水,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)饲齐,“玉大人钉凌,你說(shuō)我怎么就攤上這事∥嫒耍” “怎么了御雕?”我有些...
    開封第一講書人閱讀 162,483評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵矢沿,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我酸纲,道長(zhǎng)捣鲸,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,165評(píng)論 1 292
  • 正文 為了忘掉前任闽坡,我火速辦了婚禮栽惶,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘疾嗅。我一直安慰自己外厂,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,176評(píng)論 6 388
  • 文/花漫 我一把揭開白布宪迟。 她就那樣靜靜地躺著酣衷,像睡著了一般。 火紅的嫁衣襯著肌膚如雪次泽。 梳的紋絲不亂的頭發(fā)上穿仪,一...
    開封第一講書人閱讀 51,146評(píng)論 1 297
  • 那天,我揣著相機(jī)與錄音意荤,去河邊找鬼啊片。 笑死,一個(gè)胖子當(dāng)著我的面吹牛玖像,可吹牛的內(nèi)容都是我干的紫谷。 我是一名探鬼主播,決...
    沈念sama閱讀 40,032評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼捐寥,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼笤昨!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起握恳,我...
    開封第一講書人閱讀 38,896評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤瞒窒,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后乡洼,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體崇裁,經(jīng)...
    沈念sama閱讀 45,311評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,536評(píng)論 2 332
  • 正文 我和宋清朗相戀三年束昵,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了拔稳。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,696評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡锹雏,死狀恐怖巴比,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤轻绞,帶...
    沈念sama閱讀 35,413評(píng)論 5 343
  • 正文 年R本政府宣布腰耙,位于F島的核電站,受9級(jí)特大地震影響铲球,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜晰赞,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,008評(píng)論 3 325
  • 文/蒙蒙 一稼病、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧掖鱼,春花似錦然走、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至褐墅,卻和暖如春拆檬,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背妥凳。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工竟贯, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人逝钥。 一個(gè)月前我還...
    沈念sama閱讀 47,698評(píng)論 2 368
  • 正文 我出身青樓屑那,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親艘款。 傳聞我的和親對(duì)象是個(gè)殘疾皇子持际,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,592評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容