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

后端 未结 8 1404
耶瑟儿~
耶瑟儿~ 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:13

    Whilst the answer given by @Divya lead me to the correct solution (so I awarded the bounty), it is not a terribly clear answer! Here it is in detail:

    The standard approach to ensuring that a text view is not hidden by the on-screen keyboard is to update its frame when the keyboard is shown, as detailed in this question:

    How to resize UITextView on iOS when a keyboard appears?

    However, with iOS 7, if you change the text view frame within your handler for the UIKeyboardWillShowNotification notification, the cursor will remain off screen as described in this question.

    The fix for this issue is to change the text view frame in response to the textViewDidBeginEditing delegate method instead:

    @implementation ViewController {
        CGSize _keyboardSize;
        UITextView* textView;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
        textView = [[UITextView alloc] initWithFrame:CGRectInset(self.view.bounds, 20.0, 20.0)];    textView.delegate = self;
        textView.returnKeyType = UIReturnKeyDone;
        textView.backgroundColor = [UIColor greenColor];
        textView.textColor = [UIColor blackColor];
        [self.view addSubview:textView];
    
    
        NSMutableString *textString = [NSMutableString new];
        for (int i=0; i<100; i++) {
            [textString appendString:@"cheese\rpizza\rchips\r"];
        }
        textView.text = textString;
    
    }
    
    - (void)textViewDidBeginEditing:(UITextView *)textView1 {
        CGRect textViewFrame = CGRectInset(self.view.bounds, 20.0, 20.0);
        textViewFrame.size.height -= 216;
        textView.frame = textViewFrame;
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
        CGRect textViewFrame = CGRectInset(self.view.bounds, 20.0, 20.0);
        textView.frame = textViewFrame;
        [textView endEditing:YES];
        [super touchesBegan:touches withEvent:event];
    }
    
    @end
    

    NOTE: unfortunately textViewDidBeginEdting fires before the UIKeyboardWillShowNotification notification, hence the need to hard-code the keyboard height.

提交回复
热议问题