#import "ViewController.h"@interface ViewController ()@property (nonatomic,strong) UITextField *tf;@end@implementation ViewController- (void)viewDidLo...
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) UITextField *tf;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_tf = [[UITextField alloc]initWithFrame:CGRectMake(10, self.view.bounds.size.height - 40, 300, 30)];
_tf.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:_tf];
/*
通知中心(單例)
通知中心是一對多的,即同一個廣播可以被多個收音機接收
代理是一對一
作用:1.用來接收廣播和發起廣播
2.用通知的名字作為頻道
*/
/*
參數一:響應的類
參數二:類中響應的方法
參數三:通知的名字(即頻道)
參數四:接收類型 [註意]nil代表任何類型
*/
//:UIKeyboardWillShowNotification接收鍵盤將要顯示的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//UIKeyboardWillHideNotification接收鍵盤將要隱藏的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark - UIKeyboardWillHideNotification
//鍵盤將要隱藏
-(void)keyBoardWillHide:(NSNotification *)noti
{
//noti.userInfo是一個字典,大家可以輸出來看看字典裡面包含了什麼
//NSLog(@"%@",noti.userInfo);
//獲得彈下去後的坐標[註意是彈下後的]
CGRect keyBoardEndFrame = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//NSLog(@"--%@",NSStringFromCGRect(keyBoardEndFrame));
[UIView animateWithDuration:2 animations:^{
//改變文本框的位置,讓它跟著鍵盤一起彈起來
CGRect tfRext = _tf.frame;
tfRext.origin.y = keyBoardEndFrame.origin.y-_tf.bounds.size.height-10;
_tf.frame = tfRext;
}];
}
#pragma mark - UIKeyBoard notification
//接收到的是通知,所以參數用NSNotification
//鍵盤將要顯示
-(void)keyBoardWillShow:(NSNotification *)noti
{
CGRect keyBoardFrame = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//可以通過以下方法輸出CGRect
//NSStringFromCGRect將CGRect轉化為字元串的方式獲取Frame
//NSLog(@"%@",NSStringFromCGRect(keyBoardFrame));
//獲取鍵盤的動畫持續時間
//CGFloat keyBoardDuration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
[UIView animateWithDuration:2 animations:^{
CGRect tfRect = _tf.frame;
tfRect.origin.y = keyBoardFrame.origin.y - _tf.bounds.size.height -10;
_tf.frame = tfRect;
}];
}
#pragma mark - 當手指觸碰屏幕任何一地方時被調用
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//利用結束編輯來隱藏鍵盤
[self.view endEditing:YES];
}
@end