#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切换,键盘遮挡输入框问题
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。