如何从一个ViewController获取一个用户输入值,以便出现在另一个ViewController中? (外部/全局变量?)

时间:2013-03-28 11:43:49

标签: xcode uitextfield global-variables uilabel extern

我设置了2套Objective-C类(没有xib文件)

  1. AdultTicketCalculatorViewController
  2. //。h file

    #import <UIKit/UIKit.h>
    
    @interface AdultTicketCalculatorViewController : UIViewController {
    
        IBOutlet UITextField *Quantity;
        IBOutlet UILabel *Pricelabel;
        IBOutlet UILabel *TotalLabel;
    }
    
    -(IBAction)calculate;
    -(IBAction)clear;
    
    @end
    

    //。米

    #import "AdultTicketCalculatorViewController.h"
    
    @interface AdultTicketCalculatorViewController ()
    
    @end
    
    @implementation AdultTicketCalculatorViewController
    
    -(IBAction)calculate {
    
        float x = ([Quantity.text floatValue]);
        float c = x*15;
    
        TotalLabel.text = [[NSString alloc] initWithFormat:@"$%.2f", c];
    
    }
    
    -(IBAction)clear {
    
        Quantity.text =@"";
        Pricelabel.text =@"$15.00";
        TotalLabel.text =@"";
    
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    
    {
    
        [Quantity resignFirstResponder];
    
    }
    
    1. AdultPayNowViewController
    2. //的.h

      #import <UIKit/UIKit.h>
      
      @interface AdultPayNowViewController : UIViewController {
      
          IBOutlet UILabel *Quantity ,*Price ,*QuantitySpace ,*TotalSum ,*TotalSumSpace;
          IBOutlet UIButton *ConfirmPurchase;
      
      }
      
      @end
      

      //。米 (我还没有实施任何东西)

      我想从AdultTicketCalculator中获取一些用户输入和计算值,并以下列方式在AdultPayNowViewController中显示它们:

      1. UITextField'Quantity'(AdultTicketCalculatorViewController)出现在UILabel'QuantitySumSpace(AdultPayNowViewController)
      2. UILabel'TotalLabel'(AdultTicketCalculatorViewController)出现在UILabel'TotalSumSpace'中

1 个答案:

答案 0 :(得分:0)

你可以通过两种不同的方式实现这一目标。

1.在AdultTicketCalculatorViewController的{​​{1}}此类中保存数据,然后检索NSUserDefaults中的数据。

像这样:

AdultPayNowViewController
在AdultTicketCalculatorViewController中

whenever pushing your view place this code or in 
- (void)viewDidDisappear:(BOOL)animated{
//place here
}

并在viewWillAppear方法中重新分配文本字段值。

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject: TotalLabel.text forKey:@"TotalLabel"];
    [defaults setObject: Quantity.text forKey:@"Quantity"];
    [defaults synchronize];

在viewWillAppear方法中放置以下代码。

AdultPayNowViewController:

2.合成NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults]; TotalSumSpace.text= [defaults valueForKey:@"TotalLabel"]; QuantitySumSpace.text= [defaults valueForKey:@"Quantity"]; 中的字符串对象,并在从AdultPayNowViewController推送屏幕时指定值。