iOS - 根据键盘调整view位置

  • 效果图
02.gif

#import "ViewController.h"

#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScreenB [UIScreen mainScreen].bounds

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *txtInput;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /** 添加通知 */
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(moveKeyboard:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

-(void)moveKeyboard:(NSNotification *)notification{

    /** 键盘完全弹出时间 */
    NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] intValue];

    /** 动画趋势 */
    int curve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] intValue];
    
    /** 动画执行完毕frame */
    CGRect keyboard_frame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    /** 获取键盘y值 */
    CGFloat keyboard_y = keyboard_frame.origin.y;
    
    /** view上平移的值 */
    CGFloat offset = kScreenH - keyboard_y;

    /** 执行动画  */
    [UIView animateWithDuration:duration animations:^{
       
        [UIView setAnimationCurve:curve];
        self.view.transform = CGAffineTransformMakeTranslation(0, -offset);
    }];
    
}

//移除通知
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

知识点:通过通知监听键盘弹出,获取键盘弹出后的frame,以及完全弹出执行动画的时间--duration,以及动画的趋势curve.最后算出要平移的距离offset即可.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容