UITextView cursor below frame when changing frame

前端 未结 9 460
名媛妹妹
名媛妹妹 2020-12-01 06:50

I have a UIViewCOntrollerthat contains a UITextView. When the keyboard appears I resize it like this:

#pragma mark - Responding to          


        
9条回答
  •  悲哀的现实
    2020-12-01 07:20

    Leo Natan, you started out well but your execution was relatively inefficient. Here is a better way of doing it with less code:

    // Add Keyboard Notification Listeners in ViewDidLoad
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
    
    
    // And Add The Following Methods
    - (void)_keyboardWillShowNotification:(NSNotification*)notification
    {    
        CGRect textViewFrame = self.textView.frame;
        textViewFrame.size.height -= ([notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height + 4.0);
        self.textView.frame = textViewFrame;
    }
    
    - (void)_keyboardWillHideNotification:(NSNotification*)notification
    {
        CGRect textViewFrame = self.textView.frame;
        textViewFrame.size.height += ([notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height + 4.0);
        self.textView.frame = textViewFrame;
    }
    
    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
        NSRange typingRange = NSMakeRange(textView.text.length - 1, 1);
        [textView scrollRangeToVisible:typingRange];
    
        return YES;
    
    }
    
    - (void)dealloc {
    
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    }
    

提交回复
热议问题