1. 程式人生 > >iOS 鍵盤遮擋輸入框解決方案

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

// 方法一

- (void)addNotification {

[[NSNotificationCenterdefaultCenteraddObserver:selfselector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotificationobject:nil];

[[NSNotificationCenterdefaultCenteraddObserver:selfselector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification

object:nil];

}

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

CGRect keyboardBounds = [[[infouserInfo] objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

float f =  keyboardBounds.size.height;

self.view.frame =CGRectMake(0,0,f, 0);

}

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

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

}

// 方法二

// 開始編輯輸入彈出鍵盤

- (void)textFieldDidBeginEditing:(UITextField *)textField {

CGRect frame = textField.frame;

int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//鍵盤高度216

NSTimeInterval animationDuration =

0.30f;

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

    [UIViewsetAnimationDuration:animationDuration];

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

if(offset > 0)

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

    [UIViewcommitAnimations];

}

// 當用戶按下return鍵收回鍵盤

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [textField resignFirstResponder];

returnYES;

}

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

- (void)textFieldDidEndEditing:(UITextField *)textField {

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

}