iOS鍵盤遮擋問題解決辦法


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.結束!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM