[关闭]
@SanMao 2015-08-06T00:32:41.000000Z 字数 1977 阅读 1299

键盘的弹出和隐藏

知识补充

---利用通知的方法监听键盘位置的改变

代码:

  1. #import "ViewController.h"
  2. @interface ViewController ()
  3. // 获得TextField属性
  4. @property (weak, nonatomic) IBOutlet UITextField *textField;
  5. // 获得TextField的底部间距属性
  6. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;
  7. @end
  8. @implementation ViewController
  9. - (void)viewDidLoad {
  10. [super viewDidLoad];
  11. // 利用通知,监听键盘的位置
  12. // 添加监听
  13. // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  14. // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  15. // 最常用的通知
  16. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
  17. }
  18. - (void)dealloc{
  19. [[NSNotificationCenter defaultCenter] removeObserver:self];
  20. }
  21. - (void)keyBoardWillChange:(NSNotification *)note{
  22. // 获取键盘的frame
  23. CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
  24. // 获得键盘的动画时间
  25. CGFloat time = [UIKeyboardAnimationDurationUserInfoKey doubleValue];
  26. // 修改textfield的底部约束(屏幕的高度 - 键盘的最后Y值)
  27. [UIView animateWithDuration:time animations:^{
  28. self.bottomSpace.constant = self.view.frame.size.height - frame.origin.y;
  29. [self.view layoutIfNeeded];
  30. }];
  31. }
  32. //- (void)keyBoardWillShow:(NSNotification *)note{
  33. //
  34. // // 取出键盘的frame
  35. // CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
  36. // // 修改textField的底部约束
  37. //
  38. // CGFloat time = [UIKeyboardAnimationDurationUserInfoKey doubleValue];
  39. // [UIView animateWithDuration:time animations:^{
  40. // self.bottomSpace.constant = frame.size.height;
  41. // [self.view layoutIfNeeded];
  42. // }];
  43. //
  44. //}
  45. //
  46. //- (void)keyBoardWillHide:(NSNotification *)note{
  47. //
  48. // CGFloat time = [UIKeyboardAnimationDurationUserInfoKey doubleValue];
  49. // [UIView animateWithDuration:time animations:^{
  50. // self.bottomSpace.constant = 0;
  51. // [self.view layoutIfNeeded];
  52. // }];
  53. //
  54. //}
  55. -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  56. // 点击屏幕的时候隐藏键盘
  57. // [self.textField resignFirstResponder];
  58. // [self.textField endEditing:YES];
  59. [self.view endEditing:YES];
  60. }
  61. @end
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注