2016-03-01 107 views
0

好吧,我已經經歷了關於SO和教程的幾乎所有問題。我現在可以將我的UIView向上移動,以便在打字時可以看到它。但問題是,如果UITextField被鍵盤覆蓋,我想要移動UIView只有,因爲如果不是,那麼在移動UIView時沒有意義。我的代碼到目前爲止:當鍵盤出現時向上移動UIView

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [[NSNotificationCenter defaultCenter] addObserver:self            selector:@selector(keyboardWillShow:) 
               name:UIKeyboardWillShowNotification 
               object:nil]; 

    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(keyboardWillHide:) 
               name:UIKeyboardWillHideNotification 
               object:nil]; 
} 

#pragma mark - keyboard movements 
- (void)keyboardWillShow:(NSNotification *)notification 
{ 
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 

    [UIView animateWithDuration:0.3 animations:^{ 
     CGRect f = self.view.frame; 
     f.origin.y = -keyboardSize.height; 
     self.view.frame = f; 
    }]; 
} 

-(void)keyboardWillHide:(NSNotification *)notification 
{ 
    [UIView animateWithDuration:0.3 animations:^{ 
     CGRect f = self.view.frame; 
     f.origin.y = 0.0f; 
     self.view.frame = f; 
    }]; 
} 

任何幫助將不勝感激,謝謝。

+0

是你提交的文字和鍵盤掙扎?使用https://github.com/michaeltyson/TPKeyboardAvoiding –

+1

@Tutu如果你使用autolayout比這個鏈接可能對你有所幫助.. http://stackoverflow.com/questions/31356293/uitableview-and-uiview-with- keyboardwillshow/31356527#31356527 –

回答

2

是檢查的UITextField覆蓋鍵盤,你可以做這樣的事情:

- (void)keyboardWillShow:(NSNotification *)notification { 
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 
    if (myTextField.frame.origin.y + myTextField.frame.size.height > [UIScreen mainScreen].bounds.size.height - keyboardSize.height) { 
     // textfield is covered by keyboard 
     [UIView animateWithDuration:0.3 animations:^{ 
      CGRect f = self.view.frame; 
      f.origin.y = -keyboardSize.height; 
      self.view.frame = f; 
     }]; 
    } 
} 
+0

你能幫我解決textField的'y'位置嗎,問題是如果我從屏幕頂部添加一個約束,鍵盤出現在文本框上,如果我添加一個底部約束,空間鍵盤和文本字段之間的內容與約束相同。 – TKutal

+0

也在'如果'條件我怎麼能執行檢查所有'UITextFields',而不是'myTextField' – TKutal

+0

誰想知道更多,請檢查http://stackoverflow.com/questions/35738921/how-can -i-執行-A-簽上所有檢查-uitextfields合如果條件/ 35739035?noredirect = 1#comment59153925_35739035 – TKutal

相關問題