鍵盤遮擋輸入框的問題,鍵盤遮擋輸入框
iOS開發之“鍵盤遮擋輸入框的解決辦法”之一 -----鍵盤通知之前處理這種問題,總是在觸發輸入框編輯事件鍵盤彈出的時候,將當前的View整體向上移動,結束編輯又整體向下移,耗時耗力效率低。
在網上看了使用鍵盤通知的方法很是方便,所以寫了個demo供初學者參考!
1.在ViewController.m檔案聲明
#import "ViewController.h"@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>@property(nonatomic,strong)UITableView *tableView;//自訂表格格TableView@end@implementation ViewController
2.初始化及添加通知觀察者
1 - (void)viewDidLoad { 2 [super viewDidLoad]; 4 self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain]; 5 self.tableView.delegate = self; 6 self.tableView.dataSource = self; 7 [self.view addSubview:self.tableView]; 8 9 //鍵盤將要顯示時候的通知10 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boardWillShow:) name:UIKeyboardWillShowNotification object:nil];11 //鍵盤將要結束時候的通知12 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boardDidHide:) name:UIKeyboardDidHideNotification object:nil];13 }
3.實現通知的回應程式法
1 -(void)boardWillShow:(NSNotification *)sender{ 2 //獲得鍵盤的尺寸 3 CGRect keyBoardRect=[sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; 4 //當鍵盤將要顯示時,將tableView的下邊距增跟改為鍵盤的高度 5 self.tableView.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0); 6 } 7 8 -(void)boardDidHide:(NSNotification *)sender{ 9 //當鍵盤將要消失時,邊距還原初始狀態10 self.tableView.contentInset = UIEdgeInsetsZero;11 }
4.UITextField的代理事件(點擊鍵盤中的return按鈕,隱藏鍵盤)
1 -(BOOL)textFieldShouldReturn:(UITextField *)textField{2 //取消當前輸入框的第一響應者3 [textField resignFirstResponder];4 return YES;5 }
5.tableView的代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return 15;}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *ider = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ider]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ider]; } UITextField *TF = [[UITextField alloc] initWithFrame:CGRectMake(100, 5, 150, 20)]; TF.placeholder = @"請輸入"; TF.delegate =self; //文字框添加代理 [cell.contentView addSubview:TF]; cell.textLabel.text = @"測試"; return cell;}
@end
6.結束!