当键盘覆盖文本字段时,我使用代码使屏幕滚动。
我有一个文本字段列表,我开始将每个文本字段放在自己的 uiview 中,以用于样式和组织目的。
现在我的代码只有在我开始实际输入文本字段时才有效。这是我从苹果复制的怪物。注意:我向 registerForKeyboardNotifications 添加了一个参数,以便我可以将其包含在父类中并从任何地方调用它
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications:(UIScrollView *)scroll
{
_scroller = scroll;
[[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
{
NSLog(@"hey");
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
_scroller.contentInset = contentInsets;
_scroller.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, _activeField.frame.origin) ) {
CGPoint scrollPoint = CGPointMake(0.0, _activeField.frame.origin.y-kbSize.height);
[_scroller setContentOffset:scrollPoint animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
_scroller.contentInset = contentInsets;
_scroller.scrollIndicatorInsets = contentInsets;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
_activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
_activeField = nil;
}
我已将问题缩小到视图控制器中的这一部分
for (id subView in _tpnScroll.subviews)
{
if ([subView isKindOfClass:[UIView class]]) {
UIView *thisView = subView;
for(id textfield in thisView.subviews){
if([textfield isKindOfClass:[UITextField class]]){
[textfield setDelegate:self];
}
}
}
}
原始代码是
for (id subView in _tpnScroll.subviews){
if ([subView isKindOfClass:[UITextField class]]) {
[subView setDelegate:self];
}
}
在第一个例子中。我遍历我的 UIViews,找到 UITextfields,并将委托设置为 self(这部分我不完全理解,仍在尝试理解委托的概念)
在第二个示例中,文本字段直接位于滚动视图上,因此我直接循环浏览它们。
对不起,如果这很罗嗦。