I have a UITextField that I am adding to UITableViewCellfor use as a search field for a long list of accounts. I added it as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
if ((indexPath.section < accountsection) && (hasSearch) && (indexPath.row == 0))
{
if (!searchField)
{
searchField = [[UITextField alloc] initWithFrame:CGRectMake(20, 10, cell.frame.size.width - 40, 25)];
[searchField setEnabled:YES];
searchField.placeholder = NSLocalizedString(@"Search", @"search");
searchField.keyboardType = UIKeyboardTypeDefault;
searchField.returnKeyType = UIReturnKeySearch;
searchField.autocorrectionType = UITextAutocorrectionTypeNo;
searchField.clearButtonMode = UITextFieldViewModeAlways;
searchField.delegate = self;
[cell addSubview:searchField];
[searchField release];
}
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = @"";
cell.detailTextLabel.text = @"";
searchField.hidden = NO;
[cell bringSubviewToFront:searchField];
}
}
To detect changes in the text box, I configured UITextFieldDelegatein the header and caught the following delegate calls:
@interface AccountViewController : UITableViewController <UITextFieldDelegate> {
BOOL hasSearch;
UITextField *searchField;
...
}
In the implementation, I process these delegate methods:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSLog(@"Done editing");
[self filterAccountsBy:textField.text];
[textField resignFirstResponder];
return NO;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSLog(@"Searching for %@", string);
[self filterAccountsBy:string];
return YES;
}
However, in the second case, if I do not return YES, the text will never change; in the first, returning YES doesn't seem to affect me. But when I return YES anyway, I get nasty EXC_BAD_ACCESS.
I need to skip something in my manual by adding this UITextField to my cell, but I can't figure out what it is ... can anyone help?
Many thanks.
: , filterAccounts, . :
- (void)filterAccountsBy:(NSString *)filterstring
{
[accounts removeAllObjects];
if (([filterstring length] == 0) && (!isChooser) && (![vpmsConn isDomainLogon])) {
[accounts addObject:[[vpmsConn accounts] objectAtIndex:0]];
}
if ([filterstring length] == 0) {
[accounts addObjectsFromArray:[cache accounts]];
} else {
for (AccountItem *ac in [cache accounts])
{
BOOL found = NO;
if ([[ac.clientName uppercaseString] rangeOfString:[filterstring uppercaseString]].location != NSNotFound) {
found = YES;
}
if (found) {
[accounts addObject:ac];
}
}
}
[self.tableView reloadData];
}
. , textFieldShouldReturn, NO, . - YES , . , YES .
, , .