iOS:从TextField发送号码,并将其显示在警报中

时间:2014-02-11 04:01:57

标签: ios iphone objective-c

如何从UITextField获取号码,然后将其放入UIAlertView

标头文件

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

方法文件

- (IBAction)createStory:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mad Libs Story"

                                                message: [NSString stringWithFormat:@"First name is %@,  favorite place is %@, verb is %@, age is %@, sliderLabel number is %@, petsLabel is %@ and chooseAnimal is %ld", self.firstName.text, self.favoritePlace.text, self.verb.text, self.age.text, self.sliderLabel.text, self.petsLabel.text, (long)self.chooseAnimal.selectedSegmentIndex]
                                               delegate:self
                                      cancelButtonTitle:@"Done" otherButtonTitles:nil];
    [alert show];
}

3 个答案:

答案 0 :(得分:1)

根据我对您的问题的理解,您似乎想要获取UITextField内的数字,然后在UIAlertView中使用该数字。为此,您可以使用:

NSString *textViewString = age.text; //convert the text of the TextField to a String

然后,你可以把它放在警报视图中,比如在消息中,使用:

- (IBAction)createStory:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mad Libs Story"

                                            message: textViewString
                                           delegate:self
                                  cancelButtonTitle:@"Done" otherButtonTitles:nil];
[alert show];
}

然而,如果你想获得字面数字(在int中),那么你可以使用:

int value = [age intValue];

以int形式获取数字。您可能希望使用try-catch语句,以确保NSString可以转换为int:

@try {
   int value = [age intValue];
   //try the code above
}
@catch (NSException *e) {
    NSLog(@"Caught Exception: %@", e); 
    NSLog(@"%@ it not an integer", age);
    //if there is an NSException, log it and do the above
}
@finally {
    NSLog(@"Your number is %f", value);
    [self createStory]; //create the alert
    //if no NSException was caught, execute the above code
}

所以,让我们说UITextField包含3,那么,它会将3转换为字符串,然后转换为整数,它会创建警报视图

如果它包含apple,那么它将捕获NumberFormatException,它会记录它捕获异常,然后记录apple is not an integer,并且不会创建警报视图

答案 1 :(得分:0)

您可以按照以下方式执行此操作:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mad Libs Story" message:txtField.text delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
[alert show];

答案 2 :(得分:0)

一年前,当我刚刚学习如何编码时,我问过这个问题。现在回想一下,答案是能够从uitextfield获取数据,在这种情况下,你会使用

self.age.text

并将其分配给您想要的任何变量,或将其包含在警报对象的message参数中。