#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
#import "ViewController.h"
#import "KKTextField.h"
@interface ViewController ()<UITextFieldDelegate>
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yjd_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
for (int i = 0; i < 4; i++)
{
UITextField *textfield = [[UITextField alloc] init];
textfield.frame = CGRectMake(50, 300 + i * 50, 200, 40);
textfield.layer.cornerRadius = 5;
textfield.layer.borderColor = [UIColor redColor].CGColor;
textfield.layer.borderWidth = 1;
textfield.backgroundColor = [UIColor lightGrayColor];
textfield.tag = 200 + i;
textfield.delegate = self;
textfield.returnKeyType = i==3?UIReturnKeyDefault:UIReturnKeyNext;
[self.view addSubview:textfield];
}
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self endEdit];
}
- (void)endEdit
{
[self.view endEditing:YES];
self.view.transform = CGAffineTransformIdentity;
}
- (void)yjd_keyboardWillShow:(NSNotification *)notifi
{
//获取键盘的高度
NSDictionary *userInfo = [notifi userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGFloat keyboardHeight = [aValue CGRectValue].size.height;//键盘的高度
//获取键盘动画时间
CGFloat time = [notifi.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//获取当前第一响应状态的输入框
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView *view = [keyWindow performSelector:@selector(firstResponder)];
//输入框在当前屏幕的坐标y
CGFloat maxY = CGRectGetMaxY([view convertRect:view.bounds toView:[[[UIApplication sharedApplication] delegate] window]]);
//判断是非遮挡当前输入框,小于0遮挡,大于或等于0没有
CGFloat map = SCREEN_HEIGHT - maxY - keyboardHeight ;
NSLog(@"map = %f",map);
if (map < 0)
{
[UIView animateWithDuration:time animations:^{
self.view.transform = CGAffineTransformTranslate(self.view.transform, 0, map);
}];
}
}
#pragma mark UITextFieldDelegate 事件
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField.returnKeyType == UIReturnKeyNext)
{
UITextField *nextTextField = (UITextField *)[self.view viewWithTag:textField.tag+1];
[textField endEditing:YES];
[nextTextField becomeFirstResponder];
}
else
{
[self endEdit];
}
return YES;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
@end
iOS 多个UITextField切换,键盘遮挡输入框问题
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...