这是我为这个用途编写的一个基类。它是UIViewController
每当我想实现这种行为的子类,我只是让我的视图控制器成为这个基类的子类。
顺便说一句 - 你是对的。textFieldDidBeginEditing
在键盘出现后调用,这就是为什么你想在我的课堂上描述的键盘的回调方法中向上滚动。
另请注意,要使其正常工作,您需要将整个视图嵌入到滚动视图中,并将滚动视图的 IBOutlet 连接到它。
如果您不使用故事板,请删除 IBOutlet 部分并将您的视图嵌入到滚动视图中并在代码中建立连接。
在这之后说这里是代码:
头文件
#import <UIKit/UIKit.h>
@interface BaseViewControllerWithKeyboard : BaseViewController
@property (nonatomic, strong) IBOutlet UIScrollView *scrollView;
@property (nonatomic, strong) UITextField *activeField;
@end
实施文件
#import "BaseViewControllerWithKeyboard.h"
@interface BaseViewControllerWithKeyboard ()
@end
@implementation BaseViewControllerWithKeyboard
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self registerForKeyboardNotifications];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// Call this method somewhere in your view controller setup code.
- (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 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;
_scrollView.contentInset = contentInsets;
_scrollView.scrollIndicatorInsets = contentInsets;
}
@end