鍵盤遮擋控制項(textfield/textview.......),textfieldtextview

來源:互聯網
上載者:User

鍵盤遮擋控制項(textfield/textview.......),textfieldtextview

採用的是通知的常規方式

    // 解決鍵盤遮擋問題
//選擇didShow是因為需要鍵盤的高度
//選擇willHide是因為視圖frame重設需要優先於鍵盤消失,否則表現得不連貫
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHide:) name:UIKeyboardWillHideNotification object:nil];

觸發的方法

-(void)keyboardWasShown:(NSNotification*)notification{    //擷取鍵盤高度    NSValue* value=notification.userInfo[UIKeyboardFrameBeginUserInfoKey];    CGFloat keyBoradHeight=[value CGRectValue].size.height;    NSNumber* animationTime=notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];    double time=[animationTime doubleValue];    //擷取被遮擋控制項距離controller底部的距離    float a=self.view4.frame.origin.y+self.view4.frame.size.height;    float b = self.view.frame.size.height-a;    if (b<keyBoradHeight)    {        //動畫效果        [UIView animateWithDuration:time                         animations:^         {             //鍵盤被擋住了             CGRect viewCGrect=self.view.frame;             //視圖應該上移所以是-             viewCGrect.origin.y=viewCGrect.origin.y-(keyBoradHeight-b);             [self.view setFrame:viewCGrect];         } completion:nil];    }}-(void)keyboardWasHide:(NSNotification*)notification{    NSValue* value=notification.userInfo[UIKeyboardFrameBeginUserInfoKey];    CGFloat keyBoradHeight=[value CGRectValue].size.height;    float a=self.view4.frame.origin.y+self.view4.frame.size.height;    float b = self.view.frame.size.height-a;             CGRect viewCGrect=self.view.frame;         viewCGrect.origin.y=viewCGrect.origin.y+(keyBoradHeight-b);         [self.view setFrame:viewCGrect];}

最後移除通知

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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.