我正在尝试这样做,以便当您单击电子邮件字段并弹出键盘时,它会向上移动视图。但是现在使用此代码,无论我点击什么文本字段,它都会移动视图。我也不能让键盘解雇。不确定如何将此代码设置为仅滚动到活动字段?
代码:
- (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;
}
我有一个看起来像这样的视图(它在滚动视图上)
答案 0 :(得分:3)
为此,您可以忽略键盘显示/隐藏通知,只需使用UITextFieldDelegate
协议:
– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if([textField isEqual:self.emailTextField]){
// scroll up
}
return true;
}
– (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
if([textField isEqual:self.emailTextField]){
// scroll back to start
}
return true;
}
答案 1 :(得分:0)
– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if([textField isEqual:YourTextfieldName])
{
}
return true; // return true is needed.
}
– (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
if([textField isEqual:YourTextfieldName])
{
}
return true; //return true is needed.
}