2016-03-01 72 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

相关问题