iOS实现textfield随键盘移动

2015-12-23  本文已影响2336人  Shawn_Wang

在iOS中,点击textfield控件会弹出系统键盘,如果键盘位置在下方,那么会出现该控件被键盘遮挡的情况,这时候就需要让textfield的位置随着键盘弹出而变换。研究了一下关键代码如下。

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}

- (void)keyBoardDidShow:(NSNotification *)notif {
    NSLog(@"===keyboar showed====");
    if (keyboardDidShow) return;
//    get keyboard size
    NSDictionary *info = [notif userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
    
//  reset scrollview frame
    CGRect viewFrame = self.scrollView.frame;
    viewFrame.size.height -= keyboardSize.height;
    self.scrollView.frame = viewFrame;
    
//    scroll to current textfiled
    CGRect textfieldRect = [self.textfield frame];
    [self.scrollView scrollRectToVisible:textfieldRect animated:YES];
    keyboardDidShow = YES;
    
}

- (void)keyBoardDidHide:(NSNotification *)notif {
    NSLog(@"====keyboard hidden====");
    NSDictionary *info = [notif userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
    CGRect viewFrame = self.scrollView.frame;
    viewFrame.size.height += keyboardSize.height;
    self.scrollView.frame = viewFrame;
    if (!keyboardDidShow) {
        return;
    }
    keyboardDidShow = NO;
}

@end

对代码的解释:
UIKeyboardDidShowNotification,UIKeyboardDidHideNotification分别是键盘出现和键盘消失的通知。将ScrollView滚动到textfield控件,通过scrollRectToVisible:animated:来实现,其中scrollRectToVisible参数用于指定滚动到一个矩形区域,文档中解释为:Scrolls a specific area of the content so that it is visible in the receiver.这个矩形区域是CGRect结构体。每个视图的frame方法可以获得CGRrect结构体数据。

上一篇下一篇

猜你喜欢

热点阅读