您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 鍵盤問題:如何避免軟鍵盤擋住輸入框

編輯:iOS 相關資訊

當頁面上有靠下方的輸入框時,一旦彈出軟鍵盤,往往會把輸入框整個蓋住,使用者根本看不到自己打了什麼。這是新手常遇到的經典問題。本文示範透過 UITextFieldDelegate 監聽編輯狀態,在鍵盤出現時把視圖往上推開。

實作步驟

1)將輸入框的代理設為 self

在 xib 中把輸入框的 delegate 連到 File's Owner,或用程式碼設定:textField.delegate = self;

2)讓 ViewController 採用 UITextFieldDelegate 協議

在 ViewController.h 中宣告遵守 UITextFieldDelegate,然後在 .m 中實作以下方法即可。

程式碼

#pragma mark - UITextField Delegate

// 開始編輯:把視圖往上移動,騰出空間給鍵盤
-(void)textFieldDidBeginEditing:(UITextField *)textField {
    CGRect frame = textField.frame;
    // 鍵盤高度約為 216
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);

    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];

    // 視圖的 Y 座標向上移動 offset,為軟鍵盤騰出空間
    if (offset > 0) {
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    }

    [UIView commitAnimations];
}

// 按下 return 鍵時,鍵盤消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

// 編輯完成後,把視圖還原
-(void)textFieldDidEndEditing:(UITextField *)textField {
    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

// 觸摸 view 隱藏鍵盤
- (IBAction)View_TouchDown:(id)sender {
    // 送出 resignFirstResponder
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}

原理小結

核心思路是:在 textFieldDidBeginEditing: 中計算鍵盤會遮住多少,把整個視圖往上推;在 textFieldDidEndEditing: 中再把視圖歸位。搭配 textFieldShouldReturn: 收起鍵盤,以及一個空白處的點擊事件(View_TouchDown:)來主動關閉鍵盤,整體互動就順暢多了。若頁面元素較多,也可以改用 UIScrollView 搭配 keyboard notification 的方式來處理,思路大同小異。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved