一.创建工程项目和视图控制器
1、创建一个empty(空的)工程项目,新建一个UIViewController;
2、选中工程,右键-New File…选择“Cocoa Touch Class”-Next,给个合理的名称ViewController,再Next完成;
3、在AppDelegate.m文件包含#import "ViewController.h";
4、初始化创建ViewController的视图控制器,并用导航栏控制器包含。将之设置为根视图控制器。
#import "AppDelegate.h"
#import "ViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
_window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *vc = [[UIViewController alloc]init];
UINavigationController *nc = [[UINavigationController alloc]initWithRootViewController:vc];
_window.backgroundColor = [UIColor whiteColor];
[_window makeKeyAndVisible];
return YES;
}
二.创建UITextField及添加代理
1、在ViewController.h添加事件代理和数据源代理<UTextFieldDelegate>;
2、在ViewController.m创建并初始UITextField;
3、代理授权并添加至视图。
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITextField *textFiled = [[UITextField alloc]initWithFrame:CGRectMake(10, 460, 300, 30)];
textFiled.placeholder = @"textfield";
[self.view addSubview:textFiled];
textFiled.delegate = self;
textFiled.borderStyle = UITextBorderStyleRoundedRect;//设置圆角模式
}
三.实现弹出键盘时,输入框上移至不被隐藏
1、在ViewController.m添加并实现textFieldShouldBeginEditing方法;
2、在textFieldShouldBeginEditing内计算输入框需要上移的高度;
3、让输入框动画上移。
注:英文键盘默认高度216,其他框可以的显示高度可以适当给高点,这里给50。
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{//重写textField这个方法
NSLog(@"开始编辑");
CGFloat offset = self.view.frame.size.height - (textField.frame.origin.y+textField.frame.size.height+216+50);
NSLog(@"偏移高度为 --- %f",offset);
if (offset<=0) {
[UIView animateWithDuration:0.3 animations:^{
CGRect frame = self.view.frame;
frame.origin.y = offset;
self.view.frame = frame;
}];
}
return YES;
}
四.实现回收键盘时,输入框恢复原来的位置
1、在ViewController.m添加并实现textFieldShouldEndEditing方法;
2、让输入框动画恢复原来状态。
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{//重写textField这个方法
NSLog(@"将要结束编辑");
[UIView animateWithDuration:0.3 animations:^{
CGRect frame = self.view.frame;
frame.origin.y = 0.0;
self.view.frame = frame;
}];
return YES;
}