- 在控制器的自定義的view里面添加一個(gè)textView, 設(shè)置textView的代理, 在這個(gè)view里面實(shí)現(xiàn)這方法就可以實(shí)現(xiàn)鍵盤上移, 邏輯很簡單, 一點(diǎn)都不復(fù)雜, 根本不用通知什么的, 太麻煩, 太污染了.
- (void)textViewDidBeginEditing:(UITextView *)textView {
CGRect frame = textView.frame;
int offset = (frame.origin.y + frame.size.height + 62) - (self.frame.size.height-216.0);//鍵盤高度216 62是選擇鍵盤上方選擇文字的高度
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:0.30f];
if (offset>0) {
self.frame = CGRectMake(0.0f, -offset, self.frame.size.width, self.frame.size.height);
[UIView commitAnimations];
}
}
- (void)textViewDidEndEditing:(UITextView *)textView {
self.frame = CGRectMake(0, 0, self.width, self.height);
}
- 上面最核心的其實(shí)就是計(jì)算offset的值, 后面有注釋
- 至于textField也是類似的代理方法, 看懂了這個(gè), 那個(gè)照著一套就可以了.
我是分割線
以上是做昨天寫的, 昨晚朋友推薦神器IQKeyboardManager
, 三方框架, 絕逼好用, 在AppDelegate.m
里面寫一次就好了, 建議用pod集成, 然后在
- (void)configureKeyboardMananger {
IQKeyboardManager *mananger = [IQKeyboardManager sharedManager];
mananger.enable = YES;
mananger.shouldResignOnTouchOutside = YES;
mananger.shouldToolbarUsesTextFieldTintColor = YES;
mananger.keyboardDistanceFromTextField = 40;
mananger.enableAutoToolbar = NO;
}
然后, 在下面的方法中調(diào)用, 就可以一勞永逸, 以后工程中所有的textView或者textField在召喚神龍的時(shí)候, 就再也不會(huì)被鍵盤遮擋了.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
以上屬于 <小目標(biāo) · 一天一篇> 系列文章