Reputation: 73
I'm creating a form similar to "New Contact" from native Contacts app for iOS.
The only way I found is to create a Table View and create a custom Table View Cell.
So far so good...
Now, my TextField only get focus when I click on it, but I want to set the focus to the TextField when I click anywhere of the Table View Cell class I created.
I tried this out:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
[self.txtInputer becomeFirstResponder];
// Configure the view for the selected state
}
But it did'nt work as I wish, the focus is set to the last field of the Table.
Upvotes: 1
Views: 839
Reputation: 1817
Make a custom cell with a UITextField as a property in the .h (I've called it textField) of the class. (I've called it TextFieldCell)
Then in the didSelectRowAtIndexPath have the code below. When a cell is tapped you get a reference to the TextFieldCells then from that you can look for the textField property and call becomeFirstResponder on it. Note I have included the enums that you should use for this example. If you do not know what these are place them below your #includes and google into them. Love the enums!!
//table view sections
enum
{
TableViewSectionUsername = 0,
TableViewSectionPassword,
TableViewSectionLogin,
TableViewSectionCount
};
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
TextFieldCell *usernameCell = (TextFieldCell*)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:TableViewSectionUsername]];
TextFieldCell *passwordCell = (TextFieldCell*)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:TableViewSectionPassword]];
//switch section
switch(indexPath.section)
{
case TableViewSectionUsername:
{
[[usernameCell textField] becomeFirstResponder];
break;
}
case TableViewSectionPassword:
{
[[passwordCell textField] becomeFirstResponder];
break;
}
case TableViewSectionLogin:
{
if([[[usernameCell textField] text] isEqualToString:@""])
{
NSLog(@"Please enter a username");
[[usernameCell textField] becomeFirstResponder];
return;
}
if([[[passwordCell textField] text] isEqualToString:@""])
{
NSLog(@"Please enter a username");
[[passwordCell textField] becomeFirstResponder];
return;
}
[self dismissViewControllerAnimated:YES completion:nil];
break;
}
default:
{
break;
}
}
//deselect table cell
[_tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Upvotes: 3