How to re-size UITextView when keyboard shown with iOS 7

后端 未结 8 1411
耶瑟儿~
耶瑟儿~ 2020-12-05 03:34

I have a view controller which contains a full-screen UITextView. When the keyboard is shown I would like to resize the text view so that it is not hidden under

8条回答
  •  攒了一身酷
    2020-12-05 04:01

    Do not resize the text view. Instead, set the contentInset and scrollIndicatorInsets bottom to the keyboard height.

    See my answer here: https://stackoverflow.com/a/18585788/983912


    Edit

    I made the following changes to your sample project:

    - (void)textViewDidBeginEditing:(UITextView *)textView
    {
        _caretVisibilityTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(_scrollCaretToVisible) userInfo:nil repeats:YES];
    }
    
    - (void)_scrollCaretToVisible
    {
        //This is where the cursor is at.
        CGRect caretRect = [self.textView caretRectForPosition:self.textView.selectedTextRange.end];
    
        if(CGRectEqualToRect(caretRect, _oldRect))
            return;
    
        _oldRect = caretRect;
    
        //This is the visible rect of the textview.
        CGRect visibleRect = self.textView.bounds;
        visibleRect.size.height -= (self.textView.contentInset.top + self.textView.contentInset.bottom);
        visibleRect.origin.y = self.textView.contentOffset.y;
    
        //We will scroll only if the caret falls outside of the visible rect.
        if(!CGRectContainsRect(visibleRect, caretRect))
        {
            CGPoint newOffset = self.textView.contentOffset;
    
            newOffset.y = MAX((caretRect.origin.y + caretRect.size.height) - visibleRect.size.height + 5, 0);
    
            [self.textView setContentOffset:newOffset animated:NO];
        }
    }
    

    Removed setting old caret position at first, as well as disabled animation. Now seems to work well.

提交回复
热议问题