The following code will generate a custom autocomplete Table View autocompleteTableView
below my text field txtActivity
. How do I hide the Table View when text field is empty.
- (void)viewDidLoad
{
[super viewDidLoad];
self.txtActivity.delegate = self;
[self cofigureAutoComTableView];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)rangereplacementString:(NSString *)string
{
autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
autocompleteMArray = [[NSMutableArray alloc] init];
[autocompleteMArray removeAllObjects];
for(NSString *curString in sCategory) { //**** sCategory is a mutable array generated in another method not shown ****
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.length > 0) {
[autocompleteMArray addObject:curString];
}
}
NSLog(@"*******The autocompleteMArray : %@ ", autocompleteMArray);
[autocompleteTableView reloadData];
}
-(void)cofigureAutoComTableView
{
autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.txtActivity.frame.origin.x-10,self.txtActivity.frame.origin.y+32,self.txtActivity.frame.size.width, 120) style:UITableViewStylePlain];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self; //**** Setting this to self, is it correct???
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.hidden = YES;
[self.view addSubview:autocompleteTableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return autocompleteMArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"cellIdentifier";
UITableViewCell *cell = [self.autocompleteTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [autocompleteMArray objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath (NSIndexPath *)indexPath;
{
//**** NOT DETECTING *******
NSLog(@"Selected Cell %@", [autocompleteMArray objectAtIndex:indexPath.row]);
}