1
我正在嘗試使它在您點擊電子郵件字段時彈出鍵盤時會將視圖向上移動。但是現在使用這個代碼,無論我點擊哪個文本框,它都會移動視圖。另外我不能讓鍵盤解僱。不知道如何設置此代碼只能滾動到活動字段?UITextField在鍵盤將阻止它時移動
代碼:
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, self.emailField.frame.origin)) {
CGPoint scrollPoint = CGPointMake(0.0, self.emailField.frame.origin.y-kbSize.height);
[scrollView setContentOffset:scrollPoint animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
我有一個看起來像這樣(它是滾動型)
看看https://github.com/michaeltyson/TPKeyboardAvoiding。它使得你正在嘗試做的很簡單 – savner
你可以檢查我的答案http://stackoverflow.com/a/16481347/2315974有類似的問題。 – danypata
如果你想避免爲自己編寫代碼,有一些嵌入式開源類可以自動完成所有這些工作,比如:https://github.com/michaeltyson/TPKeyboardAvoiding – Marcel