【问题标题】:UIModalPresentationFormSheet on iPad. How to adjust UITextView height when keyboard appearsiPad 上的 UIModalPresentationFormSheet。键盘出现时如何调整UITextView的高度
【发布时间】:2013-02-09 10:56:37
【问题描述】:

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;

问题是当键盘出现时这个模态视图会跳起来。这种情况下如何计算键盘的上边框坐标?

【问题讨论】:

    标签: ios ipad keyboard


    【解决方案1】:

    你可以这样做:

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

    记得取消注册通知。

    【讨论】:

    • 自从我创建问题以来发生了很多事情。无论如何感谢您的回答。
    【解决方案2】:

    如果您不需要自己编写代码,我建议您使用https://github.com/hackiftekhar/IQKeyboardManager

    它工作得很好(对我来说,到目前为止),你需要做的就是导入它并在 AppDelegate 中添加这一行代码:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    
        //Magic one-liner
        IQKeyboardManager.sharedManager().enable = true
    
        return true
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多