問題:避免虛擬鍵盤遮蓋,主要是經過view上移下移解決,因此本身封裝工具類KeyboardUtils;代碼以下;ide
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface KeyboardUtils : NSObject - (instancetype)initWithTargetView:(UIView *)view; - (void)updateViewWithRect:(CGRect)rect; @end #import "KeyboardUtils.h" @interface KeyboardUtils () @property (nonatomic, strong) UIView *view; @property (nonatomic, assign) CGRect rect; @property (nonatomic, strong) NSDictionary *userInfo; @end CGFloat const defaultBottomOffset = 80.0f; @implementation KeyboardUtils - (instancetype)initWithTargetView:(UIView *)view { self = [super init]; if (self) { self.view = view; for (NSString *name in @[UIKeyboardWillShowNotification,UIKeyboardWillHideNotification]) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:name object:nil]; } } return self; } - (void)updateViewWithRect:(CGRect)rect { self.rect = rect; if (_userInfo) { [self avoidCoverKeyboardWithuserInfo:_userInfo frame:_rect]; } } - (void)receiveNotification:(NSNotification *)notification { NSDictionary *userInfo = notification.userInfo; CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; if ([notification.name isEqualToString:UIKeyboardWillShowNotification]) { self.userInfo = notification.userInfo; [self avoidCoverKeyboardWithuserInfo:_userInfo frame:_rect]; } else if ([notification.name isEqualToString:UIKeyboardWillHideNotification]) { self.userInfo = nil; [self moveDown:duration]; } } - (void)avoidCoverKeyboardWithuserInfo:(NSDictionary *)userInfo frame:(CGRect)frame { CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; CGRect rect = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue]; CGFloat offset = (CGRectGetMaxY(frame) + defaultBottomOffset) - (SCREEN_HEIGHT - rect.size.height); if (offset > 0) { [self moveUp:duration offset:offset]; } else { [self moveDown:duration]; } } - (void)moveUp:(NSTimeInterval)duration offset:(CGFloat)offset { [UIView animateWithDuration:duration animations:^{ _view.frame = CGRectMake(0, -offset, SCREEN_WIDTH, SCREEN_HEIGHT); }]; } - (void)moveDown:(NSTimeInterval)duration { [UIView animateWithDuration:duration animations:^{ _view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); }]; } - (void)dealloc { self.userInfo = nil; for (NSString *name in @[UIKeyboardWillShowNotification,UIKeyboardWillHideNotification]) { [[NSNotificationCenter defaultCenter] removeObserver:self name:name object:nil]; } } @end
解釋:- (void)updateViewWithRect:(CGRect)rect;方法實時的計算view需上移的距離,而後執行動畫。工具