iOS應(yīng)用開發(fā)中監(jiān)聽鍵盤事件的代碼實(shí)例小結(jié)
1.注冊(cè)監(jiān)聽鍵盤事件的通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardHide:)
name:UIKeyboardDidHideNotification
object:nil];
2.在鍵盤將要出現(xiàn)和隱藏的回調(diào)中,加入動(dòng)畫
- (void)keyboardWillShow:(NSNotification *)notif {
if (self.hidden == YES) {
return;
}
CGRect rect = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat y = rect.origin.y;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
NSArray *subviews = [self subviews];
for (UIView *sub in subviews) {
CGFloat maxY = CGRectGetMaxY(sub.frame);
if (maxY > y - 2) {
sub.center = CGPointMake(CGRectGetWidth(self.frame)/2.0, sub.center.y - maxY + y - 2);
}
}
[UIView commitAnimations];
}
- (void)keyboardShow:(NSNotification *)notif {
if (self.hidden == YES) {
return;
}
}
- (void)keyboardWillHide:(NSNotification *)notif {
if (self.hidden == YES) {
return;
}
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
NSArray *subviews = [self subviews];
for (UIView *sub in subviews) {
if (sub.center.y < CGRectGetHeight(self.frame)/2.0) {
sub.center = CGPointMake(CGRectGetWidth(self.frame)/2.0, CGRectGetHeight(self.frame)/2.0);
}
}
[UIView commitAnimations];
}
- (void)keyboardHide:(NSNotification *)notif {
if (self.hidden == YES) {
return;
}
}
3.監(jiān)聽鍵盤刪除鍵之非代理實(shí)現(xiàn)
在UITextField 和 UITextView ,如何監(jiān)聽到刪除鍵。
我看到網(wǎng)上都是用代理監(jiān)聽的,我覺得不靠譜。
其實(shí)蘋果已經(jīng)寫的很清楚了。
就在他們實(shí)現(xiàn)的協(xié)議里面~~
NS_CLASS_AVAILABLE_IOS(2_0) @interface UITextView : UIScrollView<UITextInput>
@protocol UITextInput<UIKeyInput>
@protocol UIKeyInput <UITextInputTraits>
- (BOOL)hasText;
- (void)insertText:(NSString *)text;
- (void)deleteBackward;
@end
寫的非常清楚,一看就明白。
-deleteBackward 這個(gè)方法就是刪除按鈕監(jiān)聽。
只要自己寫個(gè)子類,重寫此方法就能監(jiān)聽。
相關(guān)文章
IOS開發(fā)代碼分享之用nstimer實(shí)現(xiàn)倒計(jì)時(shí)功能
在制作IOS項(xiàng)目中,我們經(jīng)常要用到倒計(jì)時(shí)功能,今天就分享下使用nstimer實(shí)現(xiàn)的倒計(jì)時(shí)功能的代碼,希望對(duì)大家能有所幫助2014-09-09
iOS開發(fā)中對(duì)文件目錄的訪問及管理的基本方法小結(jié)
這篇文章主要介紹了iOS開發(fā)中對(duì)文件目錄的訪問及管理的基本方法小結(jié),代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-10-10
iOS開發(fā)之App主題切換解決方案完整版(Swift版)
這篇文章主要為大家詳細(xì)介紹了iOS開發(fā)之App主題切換完整解決方案,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02
右滑返回手勢(shì)和UIScrollView中手勢(shì)沖突的解決方法
這篇文章主要為大家詳細(xì)介紹了右滑返回手勢(shì)和UIScrollView中手勢(shì)沖突的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02

