解決iOS鍵盤彈出遮擋輸入框問題

當鍵盤彈出時有可能遮擋住輸入框,直接給出一個簡單的解決方案spa

- (void)viewDidLoad {server

    [super viewDidLoad];animation

    // Do any additional setup after loading the view, typically from a nib.it

    //註冊鍵盤彈起與收起通知io

    [[NSNotificationCenter defaultCenter] addObserver:selfclass

                                             selector:@selector(keyboardWillShow:)object

                                                 name:UIKeyboardWillShowNotificationselect

                                               object:nil];im

    

}call

-(void)keyboardWillShow:(NSNotification *)note

{

    NSDictionary *info = [note userInfo];

    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    _keyBoardHeight = keyboardSize.height;

    

    

    CGRect frame = _userNameTextfield.frame;

    int offset = frame.origin.y + 32 - (self.view.frame.size.height -_keyBoardHeight);

    NSTimeInterval animationDuration = 0.30f;

    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];

    [UIView setAnimationDuration:animationDuration];

        //將視圖的Y座標向上移動offset個單位,以使下面騰出地方用於軟鍵盤的顯示

    if(offset > 0)

        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);

    [UIView commitAnimations];

}  

//當用戶按下return鍵或者按回車鍵,keyboard消失

-(BOOL)textFieldShouldReturn:(UITextField *)textField

{

    [textField resignFirstResponder];

    return YES;

}

 

//輸入框編輯完成之後,將視圖恢復到原始狀態

-(void)textFieldDidEndEditing:(UITextField *)textField

{

    NSTimeInterval animationDuration = 0.30f;

    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];

    [UIView setAnimationDuration:animationDuration];

    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

    [UIView commitAnimations];

}

相關文章
相關標籤/搜索