iOS开发_UITextField视图的上升/下降 => 用系统观察者控制

0、优势说明

  • 可以获取到键盘的高度和键盘弹起和隐藏的时间。

1、多个观察者

// 添加系统通知观察者(检测键盘的显示与隐藏)
// 检测键盘的弹起
[[NSNotificationCenter defaultCenter] addObserver:self 
selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];

// 检测键盘的隐藏   
[[NSNotificationCenter defaultCenter] addObserver:self 
selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];

// 键盘弹起事件处理
- (void)keyboardShow:(NSNotification *)notification {

	// 取出键盘最终的高度
	CGFloat keyboardHeight = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;

	// 取出键盘弹出需要花费的时间
	double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

	// 设置当前视图的 frame
	CGRect frame = self.view.frame;
	frame.origin.y = -keyboardHeight;

	[UIView animateWithDuration:duration animations:^{
		self.view.frame = frame;
	}];
}

// 键盘隐藏事件处理
- (void)keyboardHide:(NSNotification *)notification {

	// 取出键盘弹出需要花费的时间
	double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

	// 设置当前视图的 frame
	CGRect frame = self.view.frame;
	frame.origin.y = 0;

	[UIView animateWithDuration:duration animations:^{
		self.view.frame = frame;
	}];
}

2、单一观察者

// 添加系统通知观察者(检测键盘的 frame 改变)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification 
object:nil];

// 键盘弹起隐藏事件处理
- (void)keyboardWillChangeFrame:(NSNotification *)notification {

	// 取出键盘最终的 frame
	CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

	// 取出键盘弹出需要花费的时间
	double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

	// 设置当前视图的 frame
	CGRect frame = self.view.frame;
	frame.origin.y = -([UIScreen mainScreen].bounds.size.height - rect.origin.y);

	[UIView animateWithDuration:duration animations:^{
		self.view.frame = frame;
	}];
}

3、视图上升或下降处理

  • 3.1 设置 frame

CGRect frame = self.view.frame;
frame.origin.y = -keyboardHeight;
[UIView animateWithDuration:duration animations:^{
	self.view.frame = frame;
}];
  • 3.2 设置 约束值

self.bottomSpacing.constant = rect.size.height;
[UIView animateWithDuration:duration animations:^{
	[self.view layoutIfNeeded];
}];
  • 3.3 设置 transform 属性

[UIView animateWithDuration:duration animations:^{
	CGFloat ty = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
	self.view.transform = CGAffineTransformMakeTranslation(0, -ty);
}];
posted @ 2022-11-10 17:51  CH520  阅读(18)  评论(0编辑  收藏  举报