Reputation: 4170
I have more than one UITextField
's in single UITableviewCell
.
I know we can identify subviews
of UITableViewCell
with using tags.
But in my scenario I have multiple UITextField
in single UITableViewCell
.
How can I provide tag to identify which UITextField
is clicked?
Upvotes: 0
Views: 232
Reputation: 11201
When you have multiple UITextFeild's
in your UITableViewCell
, give tag to each of the textfield
in your cellForRowAtIndex
method. And then when you tap on the textfield
, the UITextFieldDelegate
will get hit.
For example,textFieldShouldBeginEditing
will get hit when you tap on a textfield
.
Or, you can even add Observers to your textfield, and then you can simply validate which textfield is tapped.
If you consider the delegate method:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if(textfield.tag==1)
{
//you tapped textfield 1
}
}
Upvotes: 1
Reputation: 2962
You can set a tag like
cell.contentView.subviews.enumerated().forEach { (offset, view) in
(view as! UITextField).tag = 100 + offset
}
Then in
extension ViewController:UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.tag == 101 {
// first textField
} else if textField.tag == 102 {
// second textField
} else {
// else
}
}
}
Upvotes: 0
Reputation: 11
You can set the tag in storyboard or nib files.
Select the textfield, select the properties tab on the right, modify tag in the View section.
Upvotes: 0
Reputation: 8772
If I understand correctly, since you have more than one textField in each Cell, simply using the row as tag will still be impossible to distinguish between which textField it is from that specific row.
What I usually do in these scenarios is to encode 2 values in the tag.
For example you can save it like this:
textField.tag = indexPath.row * 1000 + TEXTFIELD_INDEX
and then, on a delegate method for that textField you would retrieve it like:
NSInteger textFieldIndex = textField.tag % 1000;
NSInteger row = textField.tag / 1000;
The textField index will be stored as the remainder of 1000 on the tag, and the row itself will be stored as the thousands.
Note: There's an implicit limitation when doing this, in which you can only have up to 1000 textFields in each cell, and about 2000000 cells. Assuming tag is a 32 bit integer. But I find that pretty reasonable :)
Upvotes: 0