Search code examples
iosobjective-cuiscrollviewuitextviewuitextviewdelegate

UIScrollView programmatically Scrolling


I have a UITextView inside a UIScrollView that needs to automatically scroll once the user starts editing it. This is because the keyboard will cover the textview.

Here is the code -

In viewDidLoad:

feedBackformView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, segmentedControl.frame.origin.x + self.segmentedControl.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)];
feedBackformView.backgroundColor = [UIColor whiteColor];
feedBackformView.scrollEnabled = YES;
feedBackformView.delegate = self;
feedBackformView.userInteractionEnabled = YES;
feedBackformView.showsVerticalScrollIndicator = YES;
feedBackformView.contentSize = CGSizeMake(320, 700);

commentsView = [[UITextView alloc] initWithFrame:CGRectMake(5, emailField.frame.origin.y + 40, 250, 150)];
commentsView.delegate = self;
commentsView.layer.borderWidth = 2.0f;
commentsView.layer.cornerRadius = 5;

and here's the delegate method implementation -

-(void)textViewDidBeginEditing:(UITextView *)textView{
    CGPoint point = textView.frame.origin;
    [scrollView setContentOffset:point animated:YES];
}

However, nothing happens.


Solution

  • your are doing fine but use feedBackformView instead of scrollView,while setting content offset in textViewDidBeginEditing:method, just have a look on below code

    feedBackformView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, 320, 200)];
    feedBackformView.backgroundColor = [UIColor whiteColor];
    feedBackformView.scrollEnabled = YES;
    feedBackformView.delegate = self;
    feedBackformView.userInteractionEnabled = YES;
    feedBackformView.showsVerticalScrollIndicator = YES;
    feedBackformView.contentSize = CGSizeMake(320, 700);
    
    commentsView = [[UITextView alloc] initWithFrame:CGRectMake(5, 40, 250, 150)];
    commentsView.delegate = self;
    commentsView.layer.borderWidth = 2.0f;
    commentsView.layer.cornerRadius = 5;
    
    [feedBackformView addSubview:commentsView];
    [self.view addSubview:feedBackformView];
    

    in textview DelegateMethod,

    -(void)textViewDidBeginEditing:(UITextView *)textView{
      CGPoint point = textView.frame.origin;
      [feedBackformView setContentOffset:point animated:YES];
     }
    

    hope it will hepls you...