//移除觀察者身份
- (void)dealloc{
[[NSNotificationCenter? defaultCenter]? removeObserver: self];
[super dealloc];
}
- (void)viewDidLoad{
[super viewDidLoad];
[self createTextField];
[self createkeyboardMonitor];
}
//將textField作為鍵盤的附加視圖
- (void)createTextField{
CGSize size = self.view.frame.size;
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(50,size.height - 100,size.width - 100,50)];
//對輸入的內(nèi)容進行加密
tf.secureTextEntry = YES;
//記錄原始frame
_originalFrame = tf.frame;
//定制附加視圖
[self customInputAccessoryViewFor:tf];
//定制主鍵盤
UIView *keyboardView = [[UIView alloc] initWithFrame:CGRectMake(0,0,size.width,size.height / 2)];
keyboardView.backgroundColor = [UIcolor yellowColor];
tf.inputView = keyboardView;
[keyboardView release];
tf.borderStyle = UITextBorderStyleBezel;
tf.tag = 100;
[self.view addsubView:tf];
[tf release];
}
- (void)customInputAccessoryViewFor:(UITextField *)tf{
CGFloat width = self.view.frame.size.width;
UIView *whiteView = [[UIview alloc] initWithFrame:CGRectMake(0.0,width,50)];
whiteView.backgroundColor = [UIcolor whiteColor];
NSArray *titles = @[@"??",@"??",@"??",@"??",@"??",@"??",@"??",@"??",@"??"];
CGFloat buttonwidth = width/titles.count;
CGFloat buttonHeight = whiteView.frame.size.height;
for (NSUInteger i = 0;i < titles.count;i++){
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(i * buttonWidth,0,buttonWidth,buttonHeight);
[button setTitle:titles[i] forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:40];
[button addTarget:self action:@selector(clickHandle:) forControlEvents:UIControlEventTouchUpInside];
[whiteView addSubview:button];
}
tf.inputAccessoryView = whiteView;
[whiteView release];
}
- (void) clickHandle:(UIButton *)button{
UITextField *tf = [self.view viewWithTag:100];
NSString *content = [tf.text stringByAppendingString:button.currentTitle];
tf.text = content;
}
//注冊第一響應(yīng)者
- (void)touchesBegan:(NSSet<UITouch *> *) withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
UITextField *tf = [self.view viewWithTag:100];
[tf resignFirstResponder];
}
//注冊觀察者身份
- (void) keyboardMonitor{
[[NSNotificationCenter defaultCenter] addObserver:self? selector:@selector(moveTextField:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moveTextField:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)moveTextField:(NSNotification *)notificcation{
UITextField *tf = [self.view viewWithTag:100];
if ([notification.name isEqualToString:UIKeyboardWillShowNotification
]){
NSValue *rectValue = notification.userInfo[UIKeyboardFrameBeginUserInfoKey];
CGrect rect;
[rectValue getValue:&rect];
//將textField加在keyboard上面
CGPoint center = tf.center;
center.y - = rect.size.height;
tf.center = center;
}else{
tf.frame = _orignalFrame;
}
}