iOS學習筆記——視圖上移與鍵盤彈回

來源:互聯網
上載者:User

在學習iOS開發的過程中總是遇見鍵盤出現時,遮蓋了輸出口UITextField,無法看到使用者自己輸出的內容。這時就需要對當前視圖做出相應的上移,當輸出結束時點擊螢幕的任意地方,使鍵盤彈回去。

第一種方法是在UITextField開始編輯前和編輯後調用的方法裡添加行動裝置檢視的方法;第二種方法是新建立一個視圖移動的方法,兩次都調用,並判斷是否做出相應移動。

把兩種方法貼出來,都需要在.h檔案中添加UITextFieldDelegate協議,還需要設定委託,此處略過

//***更改frame的值***////在UITextField 編輯之前調用方法- (void)textFieldDidBeginEditing:(UITextField *)textField{    //設定動畫的名字    [UIView beginAnimations:@"Animation" context:nil];    //設定動畫的間隔時間    [UIView setAnimationDuration:0.20];    //??使用當前正在啟動並執行狀態開始下一段動畫    [UIView setAnimationBeginsFromCurrentState: YES];    //設定視圖移動的位移    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - 100, self.view.frame.size.width, self.view.frame.size.height);    //設定動畫結束    [UIView commitAnimations];}//在UITextField 編輯完成調用方法- (void)textFieldDidEndEditing:(UITextField *)textField{    //設定動畫的名字    [UIView beginAnimations:@"Animation" context:nil];    //設定動畫的間隔時間    [UIView setAnimationDuration:0.20];    //??使用當前正在啟動並執行狀態開始下一段動畫    [UIView setAnimationBeginsFromCurrentState: YES];    //設定視圖移動的位移    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + 100, self.view.frame.size.width, self.view.frame.size.height);    //設定動畫結束    [UIView commitAnimations];}

第二種方法:

//在UITextField 編輯之前調用方法- (void)textFieldDidBeginEditing:(UITextField *)textField{    [self animateTextField: textField up: YES];    }//在UITextField 編輯完成調用方法- (void)textFieldDidEndEditing:(UITextField *)textField{    [self animateTextField: textField up: NO];}//視圖上移的方法- (void) animateTextField: (UITextField *) textField up: (BOOL) up{    //設定視圖上移的距離,單位像素    const int movementDistance = 100; // tweak as needed    //三目運算,判定是否需要上移視圖或者不變    int movement = (up ? -movementDistance : movementDistance);    //設定動畫的名字    [UIView beginAnimations: @"Animation" context: nil];    //設定動畫的開始移動位置    [UIView setAnimationBeginsFromCurrentState: YES];    //設定動畫的間隔時間    [UIView setAnimationDuration: 0.20];    //設定視圖移動的位移    self.view.frame = CGRectOffset(self.view.frame, 0, movement);    //設定動畫結束    [UIView commitAnimations];    }
使鍵盤彈回的方法,輸入觸摸的方法:

//點擊螢幕,讓鍵盤彈回- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    [self.view endEditing:YES];}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.