iOS实现textfield随键盘移动


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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值