2013-03-22 77 views
1

我有幾個文本域,每個都帶有標籤,我想單獨添加到數組中。在添加之前,我需要確定它來自哪個字段。我想對它們全部使用相同的方法,而不是爲每個文本字段設置一個方法。OBJ C - 如何從發件人獲取文本字段名稱

是否可以從發件人獲取文本字段的變量名稱?如果他們是按鈕,我可以使用[sender currentTitle],但我不知道如何從文本字段獲取標識符。

我想到的是這樣的:

- (void)makeItSo:(id)sender 
{ 
    NSString * senderName = (UITextField*)[sender stringValue] ; 
    if ([senderName isEqual: @"name"]) 
     -- add name to array 
    else if ([senderName isEqual: @"address"]) 
     -- add address to array 
} 

回答

1

是否有可能獲得來自發件人文本字段的變量名?

不,除非它是一個實例變量,在這種情況下,你可以,但你最好不要。

我不知道如何從文本框獲取的標識符

一如往常,這足以讀取documentation爲使用的UIViewtag屬性:

if ([sender tag] == SOME_CUSTOM_PRESET_VALUE) { 
    // do stuff 
} 
+0

爲什麼說最好不要使用實例變量? – 2013-03-22 22:54:15

+1

@AaronBrager不,你最好不要獲取實例變量的名字。 – 2013-03-22 22:54:41

6

如果您爲每個文本字段分配一個標籤,請使用標籤:

- (void)makeItSo:(UITextField *)sender { 
    if (sender.tag == 1) { 
     // the name text field 
    } else if (sender.tag == 2) { 
     // the address text field 
    } 
} 

這假定您已經爲IB或代碼中的每個文本字段設置了tag屬性。

這可能是有用的,所以你最終的東西是更容易閱讀來定義常量爲每個標籤:

#define kNameTextField 1 
#define kAddressTextField 2 

- (void)makeItSo:(UITextField *)sender { 
    if (sender.tag == kNameTextField) { 
     // the name text field 
    } else if (sender.tag == kAddressTextField) { 
     // the address text field 
    } 
} 

如果你有網點或實例變量,那麼你可以這樣做:

- (void)makeItSo:(UITextField *)sender { 
    if (sender == _nameTextField) { 
     // the name text field 
    } else if (sender == _addressTextField) { 
     // the address text field 
    } 
} 

其中_nameTextField_addressTextFields是文本字段的ivars。

0

例如,你可能有這些文本字段的ivars:

@property (weak) UITextField* textField1; // tag=1 
@property (weak) UITextField* textField2; // tag=2 
... 
@property (weak) UITextField* textFieldN; // tag=N 

當您收到一個動作你根本:

- (void)makeItSo:(id)sender 
{ 
    // This is the searched text field 
    UITextField* textField= [self valueForKey: [NSString stringWithFormat: @"textField%d",sender.tag] ]; 
} 

但在這一點,爲什麼不使用一個單一的財產是一個具有N個文本字段的數組,而不是N個屬性?

相關問題