---
title: "对UITextField的键盘处理方法<摘抄>"
author: "风尘哥哥"
date: "2013-08-12T23:04:23Z"
tags: []
categories: ["移动开发"]
slug: "uitextfield"
draft: false
lastmod: "2013-08-12T23:04:23Z"
id: 1923745
url: "https://eyebo.iteye.com/blog/1923745"
---

01. - (void)registerForKeyboardNotifications
02. {
03. //添加自己做为观察者，以获取键盘显示时的通知
04. \[\[NSNotificationCenter defaultCenter] addObserver:self
05. selector:@selector(keyboardWasShown:)
06. name:UIKeyboardDidShowNotification object:nil];
07. //添加自己做为观察者，以获取键盘隐藏时的通知
08. \[\[NSNotificationCenter defaultCenter] addObserver:self
09. selector:@selector(keyboardWasHidden:)
10. name:UIKeyboardDidHideNotification object:nil];
11. }
12. // 键盘出现时调用此方法
13. - (void)keyboardWasShown:(NSNotification\*)aNotification
14. {
15. //如果键盘是显示状态，不用做重复的操作
16. if (keyboardShown)
17. return;
18. //获得键盘通知的用户信息字典
19. NSDictionary* info = \[aNotification userInfo];
20. // 取得键盘尺寸.
21. NSValue* aValue = \[info objectForKey:UIKeyboardBoundsUserInfoKey];
22. CGSize keyboardSize = \[aValue CGRectValue].size;
23. // 重新设置scrollView的size
24. CGRect viewFrame = \[myScrollView frame];
25. viewFrame.size.height -= keyboardSize.height;
26. myScrollView.frame = viewFrame;
27. // 把当前被挡住的text field滚动到view中适当的可见位置.
28. CGRect textFieldRect = \[activeField frame];
29. \[myScrollView scrollRectToVisible:textFieldRect animated:YES];
30. //记录当前textField的偏移量，方便隐藏键盘时，恢复textField到原来位置
31. oldContentOffsetValue = \[myScrollView contentOffset].y;
32. //计算textField滚动到的适当位置
33. CGFloat value = (activeField.frame.origin.y+myScrollView.frame.origin.y+activeField.frame.size.height - self.view.frame.size.height + keyboardSize.height)+2.0f;
34. //value&gt;0则表示需要滚动，小于0表示当前textField没有被挡住，不需要滚动
35. if (value &gt; 0) {
36. //使textField滚动到适当位置
37. \[myScrollView setContentOffset:CGPointMake(0, value) animated:YES];
38. isNeedSetOffset = YES;//更改状态标志为需要滚动
39. }
40. //更改键盘状态标志为已显示
41. keyboardShown = YES;
42. }
43. // 键盘隐藏时调用此方法
44. - (void)keyboardWasHidden:(NSNotification\*)aNotification
45. {
46. NSDictionary* info = \[aNotification userInfo];
47. // Get the size of the keyboard.
48. NSValue* aValue = \[info objectForKey:UIKeyboardBoundsUserInfoKey];
49. CGSize keyboardSize = \[aValue CGRectValue].size;
50. // Reset the height of the scroll view to its original value
51. CGRect viewFrame = \[myScrollView frame];
52. viewFrame.size.height += keyboardSize.height;
53. myScrollView.frame = viewFrame;
54. //如果状态标志为需要滚动，则要执行textFiled复位操作
55. if (isNeedSetOffset) {
56. //oldContentOffsetValue记录了textField原来的位置，复位即可
57. \[myScrollView setContentOffset:CGPointMake(0, oldContentOffsetValue) animated:YES];
58. }
59. //复位状态标志
60. isNeedSetOffset = NO;
61. keyboardShown = NO;
62. }