在textView中輸入時避免鍵盤的遮擋 – iPhone手機開發技術文章 iPhone軟體開發教學課程

很多時候我們都在為鍵盤遮擋瞭原本就不大的屏幕時而煩惱,特別是當用戶處於編輯狀態時,鍵盤下面的內容就看不見瞭,用戶隻能處於盲打狀態瞭。現在有一種簡單的解決辦法,基本思路就是,添加通知。一直監聽鍵盤事件,在鍵盤遮擋時,將編輯器上移鍵盤的高度,鍵盤消失時,編輯區回復原來位置,ok,來兩段代碼吧
[cpp] 
– (void)viewDidLoad 

    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    self.textView=[[UITextView alloc]initWithFrame:self.view.frame]; 
    self.textView.text=@"請輸入文字"; 
    [self.view addSubview:self.textView]; 

 
– (void)didReceiveMemoryWarning 

    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 

 
– (void)viewWillAppear:(BOOL)animated 

    //註冊通知,監聽鍵盤出現 
    [[NSNotificationCenter defaultCenter]addObserver:self 
                                            selector:@selector(handleKeyboardDidShow:) 
                                                name:UIKeyboardDidShowNotification 
                                              object:nil]; 
    //註冊通知,監聽鍵盤消失事件 
    [[NSNotificationCenter defaultCenter]addObserver:self 
                                            selector:@selector(handleKeyboardDidHidden) 
                                                name:UIKeyboardDidHideNotification 
                                              object:nil]; 
    [super viewWillAppear:YES]; 

 
//監聽事件 
– (void)handleKeyboardDidShow:(NSNotification*)paramNotification 

    //獲取鍵盤高度 
    NSValue *keyboardRectAsObject=[[paramNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey]; 
     
    CGRect keyboardRect; 
    [keyboardRectAsObject getValue:&keyboardRect]; 
     
    self.textView.contentInset=UIEdgeInsetsMake(0, 0,keyboardRect.size.height, 0); 

 
– (void)handleKeyboardDidHidden 

    self.textView.contentInset=UIEdgeInsetsZero; 

 
– (void)viewDidDisappear:(BOOL)animated 

    [[NSNotificationCenter defaultCenter] removeObserver:self]; 

 

發佈留言