简体   繁体   中英

UISearchBar textDidChange not firing

I'm new to iOS programming, and I'm not sure why my textDidChange function is not firing. Searched online a bunch, but can't find out what's different between my code and everyone else's. Here's what my .h and .m files look like for this view controller:

CategoryTableViewController.h :

#import <UIKit/UIKit.h>
#import <Parse/Parse.h>

@interface CategoryTableViewController : UITableViewController


@property (weak, nonatomic) IBOutlet UIBarButtonItem *btnBack;
@property (weak, nonatomic) IBOutlet UISearchBar *txtSearchBar;

@property (strong,nonatomic) NSArray *allCategories;
@property (strong,nonatomic) NSMutableArray *filteredCategories;

//A stack containing the parent categories used to get to the current category.
@property (strong, nonatomic) NSMutableArray *parentCategories;

@end

Relevant code from CategoryTableViewController.m :

-(void)txtSearchBar:(UISearchBar*)txtSearchBar textDidChange: (NSString*)text
{

    //do something
}

I used Xcode's ctrl+click+drag to create the reference to the search bar in the header file. I put breakpoints and print statements at the start of the textDidChange code, but none of it ever gets called. Any ideas?

You need to set the delegate property of txtSearchBar to use the delegate methods. Make sure you add

    self.txtSearchBar.delegate = self; 

in ViewDidLoad()

and the delegate method

 - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    //Do something

    }

If you're using a delegate method be sure to set the delegate property on the instance that needs to call the delegate so it knows there is a delegate and where to send actions.

if you're using Interface Builder and not delegate, you need to create an IBAction function, or you can use a UIControl's subclass addTarget() method to create a callback for a given event type.

Add

self.txtSearchBar.delegate = self 

in viewDidLoad().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM