为啥显示键盘后我的滚动不起作用?
Posted
技术标签:
【中文标题】为啥显示键盘后我的滚动不起作用?【英文标题】:How come my scrolling after Keyboard is shown is not working?为什么显示键盘后我的滚动不起作用? 【发布时间】:2014-03-21 19:05:47 【问题描述】:所以我实施了 Apple 推荐的 way 管理键盘。
但如果 activeTextfield 在键盘后面,我的视图仍然不会向上或向下滚动。我觉得我缺少一些基本的东西。
这就是为什么我决定在下面发布我的所有代码。有人可以指出我做错了什么吗?
这是我的 .m 文件中的代码:
- (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);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) )
[self.scrollView scrollRectToVisible:activeField.frame animated:YES];
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
我在 .h 文件中正确声明了滚动视图,如下所示:
@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
*请注意,我在视图控制器中的视图内滚动视图(此视图属性未在 .h 中声明)。
我已经实现了以下内容:
- (void)textFieldDidBeginEditing:(UITextField *)textField
activeField = textField;
- (void)textFieldDidEndEditing:(UITextField *)textField
activeField = nil;
在我将所有文本字段嵌入滚动视图之前,下面的代码用于退出键盘。但是,它现在无法正常工作。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
UITouch *touch = [[event allTouches] anyObject];
NSLog(@"TOUCH TOUCH");
if ([_cardnumbertext isFirstResponder] && [touch view] != _cardnumbertext)
[_cardnumbertext resignFirstResponder];
NSLog(@"TOUCH TOUCH0");
【问题讨论】:
【参考方案1】:您是否在滚动视图上设置了 contentSize 属性?请尝试在调用 scrollToRectVisible:animate: 之前放置这一行。
[self.scrollView setContentSize:CGSizeMake(self.scrollView.contentSize.width, self.scrollView.frame.size.height + kbSize.height)];
【讨论】:
我在 [self.scrollView scrollRectToVisible:activeField.frame animated:YES]; 之前添加了这段代码似乎没有任何改变以上是关于为啥显示键盘后我的滚动不起作用?的主要内容,如果未能解决你的问题,请参考以下文章