2015-10-05 37 views
1

可能是一個簡單的答案,如何從textFieldDidEndEditing獲取文本?

我怎樣才能通過textField.text階段從它

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

我試圖創建一個屬性的NSString,並使其等於一個文本框的UIAlertView中到textField.text並試圖NSLog它,它回來了NULL

+1

我建議張貼,你必須創建'NSString'屬性的代碼,並試圖保存文本字段文本到它。這應該是相當微不足道的。 –

+0

@property(nonatomic,strong)NSString * string; 在接口 – farhan

+0

下的.m文件中您是否設置了UITextField的委託? – iphonic

回答

3

更新回答

要檢索UIAlertView中的文本字段的文本,可以使用textFieldAtIndex:方法。你根本不需要涉及文本字段委託。

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
    UITextField *textField = [alertView textFieldAtIndex:0]; // adjust the index if you have more than one text field. 

    NSLog(@"Text: %@", textField.text); 
} 

原來的答案

你有幾個選擇這裏。

選項1

存儲到文本字段作爲一個屬性的引用,它很可能你已經這樣做了。

@property (nonatomic, weak) IBOutlet UITextField *textField; 

然後可以從UIAlertView委託方法直接訪問,假設代表是具有參考文本字段相同的對象:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
    NSLog(@"Text: %@", self.textField.text); 
} 

選項2

如果由於某種原因,你沒有你的文本字段的引用可以從textFieldDidEndEditing:委託方法得到它,首先創建一個屬性存儲文本:

@property (nonatomic, copy) NSString *textFieldText; 

當文本字段的委託方法被調用然後更新。

- (void)textFieldDidEndEditing:(UITextField *)textField { 
    self.textFieldText = textField.text; 
} 

然後就可以在UIAlertView委託方法訪問該屬性:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
    NSLog(@"Text: %@", self.textFieldText); 
} 

+0

我忘了提及,這個TextField實際上是一個文本框在其中的uialertview – farhan

+0

我試過第二個選項,沒有工作,返回爲空 – farhan

+0

這是一個關鍵的難題,我會更新我的答案以反映這一點。 –

0

你只需要聲明的NSString對象在 @interface LoginDialogVC() { 的NSString strText中; } @end

@implementation LoginDialogVC 
-(void)textFieldDidEndEditing:(UITextField *)textField { 
    strText = textField.text; 
} 

,只要你想使用使用strText中後。

1

此代碼爲我工作:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"Do you want to call?"] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; 
alert.alertViewStyle = UIAlertViewStylePlainTextInput; 
UITextField * alertTextField = [alert textFieldAtIndex:0]; 
alertTextField.keyboardType = UIKeyboardTypeNumberPad; 
[alertTextField setTextAlignment:NSTextAlignmentCenter]; 
[alert show]; 

和代表:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
if (buttonIndex==1) { 
    return; 
} 
UITextField *title1;// = [alertView textFieldAtIndex:0]; 

title1= [alertView textFieldAtIndex:0]; 
NSString *messageStr = title1.text; 

if ([messageStr isEqualToString:@""]) { 
    return; 
}}