2013-02-09 62 views
7

UITextView是模態控制器視圖的子視圖。當鍵盤出現時,我需要降低UITextView的高度,以使UITextView的底部邊界y座標等於鍵盤的頂部y座標。 I'getting鍵盤高度iPad上的UIModalPresentationFormSheet。如何在出現鍵盤時調整UITextView高度

CGRect frameBegin = [[notification.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] ; 
CGRect frameEnd = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; 

CGRect resultBegin = [self.view convertRect:frameBegin fromView:nil]; 
CGRect resultEnd = [self.view convertRect:frameEnd fromView:nil]; 

CGFloat kbdHeight = resultBegin.origin.y - resultEnd.origin.y; 

的問題是,這種模式的看法跳起來鍵盤出現時。在這種情況下如何計算鍵盤的頂部邊界座標?

回答

4

你可以這樣做:

1. Register for keyboard notifications: 

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(myTextViewHeightAdjustMethod:) 
              name:UIKeyboardWillShowNotification 
              object:nil]; 

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(myTextViewHeightAdjustMethod:) 
              name:UIKeyboardDidShowNotification 
              object:nil]; 

2. Calculate intersection and adjust textView height with the bottom constraint 

    - (void)myTextViewHeightAdjustMethod:(NSNotification *)notification 
    { 
     NSDictionary *userInfo = [notification userInfo]; 
     CGRect keyboardFinalFrame = [[userInfo emf_ObjectOrNilForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; 

     CGPoint keyboardOriginInView = [self.view convertPoint:keyboardFinalFrame.origin fromView:nil]; 

      CGFloat intersectionY = CGRectGetMaxY(self.view.frame) - keyboardOriginInView.y; 

      if (intersectionY >= 0) 
      { 
       self.textViewBottomConstraint.constant = intersectionY + originalTextViewBottomConstraint; 

       [self.textView setNeedsLayout]; 
    } 

記住要註銷的通知。

+0

自創建問題以來發生了很多事情。無論如何謝謝你的答案。 – Michael 2015-05-15 19:52:10

0

如果您不需要自己編寫的代碼爲了這個,我建議使用https://github.com/hackiftekhar/IQKeyboardManager

它的偉大工程(對我來說,到目前爲止)和所有你需要做的就是導入並添加這一行代碼在AppDelegate:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

    //Magic one-liner 
    IQKeyboardManager.sharedManager().enable = true 

    return true 
} 
相關問題