ios 开发 键盘 android,iOS开发之键盘的弹出与隐藏

当界面上需要弹出键盘时,首先要注册通知监听器。

通知中心(NSNotificationCenter)提供了方法来注册一个监听通知的监听器(Observer)

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;

observer:监听器,即谁要接收这个通知

aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入

aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知

anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知

- (void)viewDidLoad {

[super viewDidLoad];

// 监听键盘通知

//弹出键盘通知

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

//收起键盘通知

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

//其实以上两个通知,键盘的弹出和隐藏用一个通知可以代替

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

}

#pragma mark - 键盘处理

- (void)keyboardWillChangeFrame:(NSNotification *)note {

//取出键盘最终的frame

CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

//取出键盘弹出需要花费的时间

double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

//修改约束

//屏幕高度 - 键盘的Y值

self.bottomSpace.constant = [UIScreen mainScreen].bounds.size.height - rect.origin.y;

[UIView animateWithDuration:duration animations:^{

[self.view layoutIfNeeded];

}];

}

- (void)keyboardWillShow:(NSNotification *)note {

//取出键盘最终的frame

CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

//取出键盘弹出需要花费的时间

double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

//修改约束

self.bottomSpace.constant = rect.size.height;

[UIView animateWithDuration:duration animations:^{

[self.view layoutIfNeeded];

}];

}

- (void)keyboardWillHide:(NSNotification *)note {

//取出键盘弹出需要花费的时间

double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

//修改约束

self.bottomSpace.constant = 0;

[UIView animateWithDuration:duration animations:^{

[self.view layoutIfNeeded];

}];

}

当滚动tableview时,就收起键盘:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {

//方式一

[self.view endEditing:YES];

//方式二:用textField

[self.textField endEditing:YES];

//方式三:

[self.textField resignFirstResponder];

}

当viewcontroller销毁时,需要移除这个通知监听:

- (void)dealloc {

//移除通知监听

[[NSNotificationCenter defaultCenter]removeObserver:self];

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值