【发布时间】:2014-01-12 13:00:29
【问题描述】:
虽然这个问题已经在很多场合被描述过,但我在参考和 IOS7 和 Apple 提出的解决方案的上下文中提出了这个问题,该解决方案在此处的文档中有所描述:
问题:键盘覆盖了文本视图。解决方案:使用苹果建议的方法,将观察者附加到键盘事件,将 UIScrollView uo 滚动到键盘高度。
我已经创建了单个 texfield 的简单实现,它是视图控制器中滚动视图的子视图,确保视图控制器是两者的代表,并确保调用正确的方法。
TestViewController.h
#import <UIKit/UIKit.h>
@interface TestViewController : UIViewController <UITextFieldDelegate, UIScrollViewDelegate>
@end
TestViewController.m
#import "TestViewController.h"
@interface TestViewController ()
@property (weak, nonatomic) IBOutlet UITextField *testTextField;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end
@implementation TestViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self registerForKeyboardNotifications];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)registerForKeyboardNotifications
{
NSLog(@"registerForKeyboardNotifications got called");
[[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(@"keyboardWasShown got called");
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, self.testTextField.frame.origin) ) {
[self.scrollView scrollRectToVisible:self.testTextField.frame animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
NSLog(@"keyboardWillBeHidden got called");
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return TRUE;
}
@end
【问题讨论】:
-
编辑:事实证明 Apple 文档有问题。在这里修复并回答stackoverflow.com/a/4837510/656959
标签: ios7 uiscrollview keyboard