码迷,mamicode.com
首页 > 移动开发 > 详细

IOS键盘弹出文本输入框上移

时间:2016-04-20 00:26:20      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

刚开始做IOS,做的不好,还望朋友们多多指教,谢谢!

技术分享技术分享

#import "ViewController.h"

@interface ViewController ()<UITextFieldDelegate>
{
    UIView *activeView;
    UITextField *textField;
    float keyBoardHeight;
    float w, h;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    w = self.view.bounds.size.width;
    h = self.view.bounds.size.height;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    activeView = [[UIView alloc] initWithFrame:CGRectMake(0, h - 40, w, 45)];
    activeView.backgroundColor = [UIColor colorWithRed:0.4 green:0.3 blue:0.5 alpha:1.0];
    [self.view addSubview:activeView];
    
    
    textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, w-20, 25)];
    textField.backgroundColor = [UIColor lightGrayColor];
    textField.keyboardAppearance = UITextBorderStyleRoundedRect;
    textField.delegate = self;
    [activeView addSubview:textField];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [[NSNotificationCenter defaultCenter] postNotificationName:UIKeyboardWillShowNotification object:nil];

    return YES;
}

- (void)keyboardWillAppear:(NSNotification*)noti{
    
    NSDictionary *keyBInfo = [noti userInfo];
    NSValue *value = [keyBInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [value CGRectValue];
    keyBoardHeight = keyboardFrame.size.height;
    
    [UIView animateWithDuration:1 animations:^{
        CGRect tFrame = activeView.frame;
        tFrame.origin.y = h - keyBoardHeight - 40;
        activeView.frame = tFrame;
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [textField resignFirstResponder];
    [UIView animateWithDuration:0.3 animations:^{
        CGRect tFrame = activeView.frame;
        tFrame.origin.y = h - 40;
        activeView.frame = tFrame;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

 

IOS键盘弹出文本输入框上移

标签:

原文地址:http://www.cnblogs.com/garywong1949/p/5410725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!