簡體   English   中英

如何在UIAlertView中從UITextField獲取文本

[英]How do I get text from UITextField in an UIAlertView

我正在嘗試向tableview添加一個新單元格,並使用UITextField彈出一個警報,以允許用戶輸入他們希望為新單元格提供的標題。 我有代碼在按下“+”按鈕時用UITextField彈出警報,以及添加新單元格的代碼,但是我不知道如何從UITextField獲取文本以將其插入到單元格的標題中。

這是我彈出警報的代碼:

UIAlertView* alertPopUp = [[UIAlertView alloc] init];
 [alertPopUp setDelegate:self];
 [alertPopUp setTitle:@"Enter event title"];
 [alertPopUp setMessage:@" "];
 [alertPopUp addButtonWithTitle:@"Cancel"];
 [alertPopUp addButtonWithTitle:@"OK"];

 UITextField * eventNameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
 [eventNameField setBackgroundColor:[UIColor whiteColor]];
 [alertPopUp addSubview:eventNameField];
 [alertPopUp show];

我的alertView操作是:

    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
 NSString *buttonTitle=[alertView buttonTitleAtIndex:buttonIndex];
 if([buttonTitle isEqualToString:@"Cancel"]) {
  return;
 }
 else if([buttonTitle isEqualToString:@"Ok"]) {

 }

}

當按下“確定”時,如何從eventNameField獲取文本並將其添加到名為eventList的mutablearray中? 謝謝!

將eventNameField上的標記設置為有意義的內容

eventNameField.tag = 1001;

然后在alertViewDelegate里面你可以使用 - [UIView viewWithTag:]來獲取TextField

UITextField* textField = (UITextField*)[alertView viewWithTag:1001];

eventNameField.text應該為您提供值

//declare the array
NSMutableArray* eventList = [NSMutableArray array];

//set its value
[eventList addObject:eventNameField.text];

舊的答案沒有利用UIAlertView的變化。

在iOS 5及更高版本中,有一種在警報視圖上使用UITextfield的簡便方法:

   UIAlertView *alertPopUp = [[UIAlertView alloc] initWithTitle:@"Enter event title" message:@"" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];

    alertPopUp.alertViewStyle = UIAlertViewStylePlainTextInput;
    self.alertTextField = [message textFieldAtIndex:0];
    self.alertTextField.keyboardType = UIKeyboardTypeAlphabet;
    alertPopUp.delegate = self;
    [alertPopUp show];
    [self.alertTextField becomeFirstResponder];

alertTextField的設置方式如下:

@propery (nonatomic, strong) UITextField *alertTextField;

然后,您可以在委托響應中訪問alertTextField:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
   NSString *buttonTitle=[alertView buttonTitleAtIndex:buttonIndex];
   if([buttonTitle isEqualToString:@"Cancel"]) {
       return;
   }
   else if([buttonTitle isEqualToString:@"Ok"]) {
       NSLog(@"your text string is %@", self.alertTextField.text);
   }
}

您還可以給alertView一個唯一的標記,並比較標記號,而不是使用@property保存對它的引用。

DHamrick可能有更好的解決方案,但又找到了一個可行的解決方案。

您可以使用[alertView子視圖]獲取alertView內的所有子視圖(返回NSCFArray),然后您只需要找到UITextField類的子視圖,在您的情況下,您可以使用:

[[[alertView subviews] objectAtIndex:4] text]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM