美文网首页
iOS实现textfield随键盘移动

iOS实现textfield随键盘移动

作者: Shawn_Wang | 来源:发表于2015-12-23 23:06 被阅读2336次

    在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结构体数据。

    相关文章

      网友评论

          本文标题:iOS实现textfield随键盘移动

          本文链接:https://www.haomeiwen.com/subject/ftyvhttx.html