6

UITextView 是模态控制器视图的子视图。当键盘出现时,我需要降低 UITextView 的高度,以便 UITextView 的底部边框 y 坐标等于键盘的顶部 y 坐标。我得到键盘高度

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

2 回答 2

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];
    }

记得取消注册通知。

于 2015-05-14T18:49:28.180 回答
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
}
于 2016-04-19T10:50:13.493 回答