Objective C: use tag for textfield
I have this code
- (IBAction) addNumberField {
if ([firstField.text intValue] == 3)
{
firstField.text = @"0";
}
else
{
int num = [firstField.text intValue];
n开发者_Go百科um = num + 1;
firstField.text = [[NSNumber numberWithInt:num] stringValue];
}
}
you can see that with this IBAction I increase textfield value with a button and the range is 0-3. But I want use this IBAction also for an other textfield not only firstField, but also for secondField (second textField). I think that I should use tag, but I don't know the way. Can you help me?
In general, when you need to apply the same code to different objects or values, you define a method like this:
- (void)updateNumberField:(UITextField *)textField {
int num = [textField.text intValue];
num = (num + 1) % 4; // this will wrap num to the range [0, 3]
textField.text = [NSString stringWithFormat:@"%d", num];
}
- (IBAction)addNumberField {
[self updateNumberField:firstField];
[self updateNumberField:secondField];
// you can do the same for whatever field you like
}
It is, of course, possible to use tags by assigning num
to textField.tag
in updateNumberField:
method. It will save you a conversion from NSString
to int
.
If you need to attach any additional values to your text fields, consider making a subclass and add all the required functionality to it.
assign tag to each text field in IB if you are using IB and in code call setTag to each textfield.
In .h
file we declare the code for textfield, i.e:
uitextfield *tf;
In .m
file we implement that one.
In viewdidload:
{
tf=[uitextfield alloc]initwithframe:(cgrectmake(x axis,y axis, width, height))];
[self.view addsubview:tf];
}
精彩评论