iOS实现textfield随键盘移动

来源:互联网 发布:我知这世界露水日文 编辑:程序博客网 时间:2024/05/20 18:55

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


- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyBoardDidShow:)name:UIKeyboardDidShowNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyBoardDidHide:)name:UIKeyboardDidHideNotificationobject:nil];

}

- (void)viewWillDisappear:(BOOL)animated {

        [super viewWillDisappear:animated];

    [[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardDidShowNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardDidHideNotificationobject:nil];

}

- (void)keyBoardDidShow:(NSNotification *)notif {

    NSLog(@"===keyboar showed====");

    if (keyboardDidShow) return;// get keyboard size

    NSDictionary *info = [notif userInfo];

    NSValue *aValue = [infoobjectForKey: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.textfieldframe];

    [self.scrollView scrollRectToVisible:textfieldRect animated:YES];

    keyboardDidShow = YES;

}

- (void)keyBoardDidHide:(NSNotification *)notif {

    NSLog(@"====keyboard hidden====");

    NSDictionary *info = [notif userInfo];

    NSValue *aValue = [infoobjectForKey: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;

}

对代码的解释:

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



0 0
原创粉丝点击