iOS解决TextField被键盘遮住的问题

本文介绍了一种在iOS应用中处理键盘弹出时ScrollView内容偏移的方法。通过监听键盘展示与隐藏的通知来动态调整ScrollView的contentInset,确保输入框保持可见。同时实现了UITextField编辑开始与结束时的响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


首先,我们在ViewController.h中

@interface ViewController : UIViewController<UITextFieldDelegate>


@property (strong, nonatomic) UIScrollView* scrollView;

@property (strong, nonatomic) UITextField* textField;

@end


之后在ViewController.m


@implementation ViewController


- (void)viewDidLoad

{

   [superviewDidLoad];


self.scrollView = [[UIScrollViewalloc] initWithFrame:CGRectMake(0, 0, 320, 600)];

   [self.viewaddSubview:self.scrollView];



self.textField = [[UITextFieldalloc] initWithFrame:CGRectMake(50, 400, 100, 30)];

self.textField.backgroundColor = [UIColorwhiteColor];

   [self.scrollViewaddSubview:self.textField];


   [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(textShowBegin:) name:UIKeyboardWillShowNotificationobject:nil];


   [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyBoardDidHidden) name:UIKeyboardWillHideNotificationobject:nil];


   [self.textFieldaddTarget:selfaction:@selector(textFieldResign) forControlEvents:UIControlEventEditingDidEndOnExit];



}

-(void)keyBoardDidHidden

{

self.scrollView.contentInset = UIEdgeInsetsZero;

}

-(void)textFieldResign

{

   [self.textFieldresignFirstResponder];

}




-(void)textFieldDidBeginEditing:(UITextField *)textField

{

self.textField = textField;

}

-(void)textShowBegin:(NSNotification*)aNotification

{

NSDictionary* info = aNotification.userInfo;

NSLog(@"%@",info);


CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0);



self.scrollView.contentInset = contentInsets;

//获取整个视图的大小和位置

CGRect aRect = self.view.frame;


   aRect.size.height -= kbSize.height;

if (!CGRectContainsPoint(aRect, self.textField.frame.origin)) {


CGPoint scrollPoint = CGPointMake(0, self.textField.frame.origin.y - kbSize.height);

       [self.scrollViewsetContentOffset:scrollPoint animated:YES];


   }


}

下载地址 "TextFieldKB1119.zip"  http://vdisk.weibo.com/s/Et2R_



本文出自 “7087095” 博客,请务必保留此出处http://7097095.blog.51cto.com/7087095/1222128

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杜甲同学

感谢打赏,我会继续努力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值