tags:

views:

28

answers:

4

Hi all,

I have 3 UITextFileds on a view, and I want to apply logic in UITextFieldDelegate method only in two of them, how do I determine the UITextField that triggered the call backs?

Many thanks in Advance!

+1  A: 

if you are using the delegate methods, such as - (void)textFieldDidEndEditing:(UITextField *)textField all you need to do is do something like

- (void)textFieldDidEndEditing:(UITextField *)textField
{
if (textField == myFirstTextField)
{
//blah
}
else if (textField == mySecondTextField)
{
//etc etc.
}
else
{
//WHEE!
}
}//method end
Jesse Naugher
+1  A: 

You can compare the pointers if you keep references to them in your class ivars or you can use UIView's tag property, whichever you like more.

Costique
+1  A: 

The delegate methods have a textfield parameter which is a point to the textfield object. You can compare that parameter to your textfield objects to see which one it is.

UITextField *field1, *field2, *field3;

In your delegate method you can compare the parameter:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range  replacementString:(NSString *)string
{
    if (textField == field1) {
        // do something special for field 1
    } ...
progrmr
+3  A: 

Usually, simple pointer comparison works, since you just want to check for object identity.

-(BOOL)textFieldShouldReturn:(UITextField*)textField {
   if (textField != theIgnoredTextField) {
      ...

Alternatively, you could assign .tags to the text field.

-(BOOL)textFieldShouldReturn:(UITextField*)textField {
   if (textField.tag != 37) {
      ...

The advantage is you don't need to store the reference to theIgnoredTextField, and the tag can be set from Interface Builder, but it relies on a recognizing magic number "37".

KennyTM
...or the compiled enumerated constant `KTMIgnoredTextFieldTag`. I use that a lot in table view cell configuration.
Graham Lee
@Graham: That's good if the view is constructed entirely from code, but AFAIK in IB you can't enter a non-integer like "KTMIgnoredTextFieldTag".
KennyTM
No, but you do reduce the profusion of magic numbers from everywhere you might need to use the textfield to 2.
Graham Lee
You can always assign the tag to a IB made element when its ViewController's viewDid/WillLoad method. That said, you should ditch IB but for the most basic things. Creating everything in code is faster and provides a cleaner approach.
jamone