Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable UIScrollView scrolling when UITextField becomes first responder

When a UITextField embedded in a UIScrollView becomes the first responder (for example, by the user typing in some character), the UIScrollView scrolls to that Field automatically. Is there any way to disable that?

Duplicate rdar://16538222

like image 964
Rabih Avatar asked Jan 03 '11 15:01

Rabih


2 Answers

Building on Moshe's answer... Subclass UIScrollView and override the following method:

- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated 

Leave it empty. Job done!


In Swift:

class CustomScrollView: UIScrollView {     override func scrollRectToVisible(_ rect: CGRect, animated: Bool) { } } 
like image 174
Luke Avatar answered Sep 21 '22 10:09

Luke


I've been struggling with the same problem, and at last I've found a solution.

I've investigated how the auto-scroll is done by tracking the call-trace, and found that an internal [UIFieldEditor scrollSelectionToVisible] is called when a letter is typed into the UITextField. This method seems to act on the UIScrollView of the nearest ancestor of the UITextField.

So, on textFieldDidBeginEditing, by wrapping the UITextField with a new UIScrollView with the same size of it (that is, inserting the view in between the UITextField and it's superview), this will block the auto-scroll. Finally remove this wrapper on textFieldDidEndEditing.

The code goes like:

- (void)textFieldDidBeginEditing:(UITextField*)textField {       UIScrollView *wrap = [[[UIScrollView alloc] initWithFrame:textField.frame] autorelease];       [textField.superview addSubview:wrap];       [textField setFrame:CGRectMake(0, 0, textField.frame.size.width, textField.frame.size.height)];      [wrap addSubview: textField];   }    - (void)textFieldDidEndEditing:(UITextField*)textField {     UIScrollView *wrap = (UIScrollView *)textField.superview;     [textField setFrame:CGRectMake(wrap.frame.origin.x, wrap.frame.origin.y, wrap.frame.size.width, textField.frame.size.height)];   [wrap.superview addSubview:textField];     [wrap removeFromSuperview];   }   

hope this helps!

like image 42
Taketo Sano Avatar answered Sep 20 '22 10:09

Taketo Sano