Question

In my app i have UITextField on view of VC1(UIViewController). When i change text in textfield i call pushing of another controller VC2 with UISearchBar on its view. After pushing im assigning UISearchBar text to the textfield text from VC1.

On xib my textfield already have some text "Test string".

When I'm append VC1 textfield with any char - VC2 pushing and text on searchbar is normal.

But when I'm press backspace key on iPhone keyboard - VC2 pushed and text on searchfield start deleting char by char, while whole string not been empted. It happend because delegate method calls recursively.

How to fix that behaviour of UISearchBar? I mush to have searchbar active with keyboard opened when VC2 appears! It's main condition. Sure, if i'll remove [self.searchBar becomeFirstResponder] all will works fine.

Some code here:

@implementation ViewController1

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range  replacementString:(NSString *)string
{
NSString * resultString = [textField.text stringByReplacingCharactersInRange:range withString:string];
ViewController2 * vc2 = [ViewController2 new];
[self.navigationController pushViewController:vc2 animated:YES];
[vc2 loadText: resultString];
return NO;
}

@end


@implementation ViewController2

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.searchBar becomeFirstResponder];
}

- (void) loadText: (NSString *) text
{
    self.searchBar.text = text;
}

@end

Sample source code of the problem: http://yadi.sk/d/NJmTLot73_vrE

Was it helpful?

Solution

I've gone through the code and for some reason the delete/backspace key is getting called repeatedly by the UIKeyboard's Accessibility function. I haven't been able to find a reason yet but one workaround is to put the [self.searchBar becomeFirstResponder]; line into viewDidAppear instead of viewWillAppear - is that an acceptable workaround? The keyboard animation is slightly different but I'm not sure how sensitive your needs are to that.

OTHER TIPS

I've been experiencing strange UISearchBar animations on iOS 7. Solved the problem by putting my becomeFirstResponder call in viewDidAppear with a delay of 0.1.

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self.searchBar performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.1];
}

You have a recursive call in your code.

self.searchBar.text = text;

calls to

textField:shouldChangeCharactersInRange:

which in turn calls to

loadText:

What you can do is remove the delegate from the searchBar uitextfield, set the text and then return the delegate. Something like this:

- (void) loadText: (NSString *) text
{
    self.searchBar.delegate = nil;
    self.searchBar.text = text;
    self.searchBar.delegate = vc1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top