iOS 鍵盤遮擋輸入框的解決方案

一、app

第三方:
TPKeyboardAvoiding
或者
防止鍵盤擋住輸入框
- (void)viewDidLoad{
	//註冊監聽,防止鍵盤遮擋視圖
   	 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
   	 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void) dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:selfname:nilobject:nil];
}
#pragma mark - textField
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    top = self.mainTableView.contentOffset.y;//該輸入框的偏移量
    clickFlg = textField.tag;//判斷點擊了哪一個輸入框
}
#pragma mark - 監聽
- (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.viewconvertRect: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];
    animationDuration += 0.1f;
    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
    [UIView beginAnimations:nil context:NULL];
    [UIViewsetAnimationDuration:animationDuration];
    
    CGFloat clickTop = 0;
    //64:頂部高度
    clickTop = CGRectGetHeight(self.mainTableView.tableHeaderView.frame) + [self tableView:self.mainTableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:clickFlg inSection:0]]*(clickFlg+1) + 64;
    if (keyboardTop > 0 && keyboardTop < clickTop) {
        [self.mainTableViewsetContentOffset:CGPointMake(0, fabsf(keyboardTop - clickTop)) animated:YES];
    }    
    //[self.mainScrollView setContentOffset:CGPointMake(0, keyboardTop) animated:YES];
    [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.view cache:YES];
    
    [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];
    [UIViewsetAnimationDuration:animationDuration];
    
    [self.mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    [UIView commitAnimations];
}

二、ide

// 點擊背景退出鍵盤
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backupgroupTap:)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer: tapGestureRecognizer];   // 只須要點擊非文字輸入區域就會響應
    [tapGestureRecognizer setCancelsTouchesInView:NO];
-(void)backupgroupTap:(id)sender{
    [self.phoneField resignFirstResponder];
}
**********************************************************************************************************************************
    CGFloat _bottom;
    CGPoint _oldOffset;
    CGFloat _keyboardTop;
#pragma mark - 鍵盤遮擋輸入框處理
// 監聽鍵盤彈出通知
- (void) registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)unregNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
// 開始編輯輸入框,得到輸入框底部在屏幕上的絕對位置
-(void)textFieldDidBeginEditing:(UITextField *)textField {
    [self registerForKeyboardNotifications];
    UIWindow *window=[[[UIApplication sharedApplication] delegate] window];
    CGRect rect=[textField convertRect: textField.bounds toView:window]; // 在屏幕上的座標
    _bottom = rect.origin.y + rect.size.height; // 得到輸入框底部在屏幕上的絕對位置
}
// 鍵盤彈出,得到鍵盤高度,計算界面須要偏移的距離
- (void) keyboardWillShow:(NSNotification *) notification {
    _oldOffset = self.mainScrollView.contentOffset;
    [self unregNotification];
    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];
    _keyboardTop = keyboardRect.origin.y;
    
    // 計算出須要偏移的距離offset,即輸入框bottom與鍵盤top的距離
    float offset = _bottom - _keyboardTop;
    if(offset > 0) { // offset爲正,說明輸入框被鍵盤遮擋
        NSTimeInterval animationDuration = 0.3f;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        offset += 5;
        self.mainScrollView.contentOffset = CGPointMake(0, _oldOffset.y + offset);
        [UIView commitAnimations];
    }
}
//鍵盤隱藏,將視圖恢復到原始狀態
- (void) keyboardWillHidden:(NSNotification *) notif {
    self.mainScrollView.contentOffset = _oldOffset;
}

三、ui

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //add notification
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)keyboardChange:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect keyboardEndFrame;
    
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    
    //adjust ChatTableView's height
    if (notification.name == UIKeyboardWillShowNotification || notification.name == UIKeyboardWillChangeFrameNotification) {
        self.bottomConstraint.constant = keyboardEndFrame.size.height;
    }else{
        self.bottomConstraint.constant = 0;
    }
    
    [self.view layoutIfNeeded];
    
    //adjust UUInputFunctionView's originPoint
    CGRect newFrame = self.viewPing.frame;
    newFrame.origin.y = keyboardEndFrame.origin.y - newFrame.size.height;
    self.viewPing.frame = newFrame;
    
    [UIView commitAnimations];
    
}

這是寫的一個很簡單的例子spa

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.loginBtn.layer.cornerRadius=4.0;
    self.loginBtn.backgroundColor=[UIColor colorWithRed:248.0/255 green:181.0/255 blue:18.0/255 alpha:1];
    self.bgview.userInteractionEnabled=YES;
    UITapGestureRecognizer *singalTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backKeyboard)];
    [self.view addGestureRecognizer:singalTap];
    self.password.tag=0;
    [self.password addTarget:self action:@selector(textFieldDidBeginEditing:) forControlEvents:UIControlEventEditingDidBegin];
    
    [self.password addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
    
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)backKeyboard{
    [self.bgview endEditing:YES];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField.tag==0) {
        [self moveView:-68];
    }
    
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag==0) {
        [self moveView:68];
    }
    
}
-(void)moveView:(float )move{
    NSTimeInterval animationDuration=0.30f;
    CGRect frame=self.bgview.frame;
    frame.origin.y+=move;
    [UIView beginAnimations:@"ResizeViewFrame" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.bgview.frame=frame;
    [self.bgview layoutIfNeeded];
    [UIView commitAnimations];  
}
@end
相關文章
相關標籤/搜索