iOS开发 textField被键盘遮住的时候自动上移

一.创建工程项目和视图控制器

      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;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值