我试图使在文本字段中输入的值更改下一个 ViewController 上的背景颜色,但该值无法在第二个视图控制器中读取。我如何使它能够识别价值?
视图控制器.h:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
IBOutlet UITextField *valueTextField;
}
- (IBAction)save:(id)sender;
@end
视图控制器.m:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
// Get the stored data before the view loads
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int value = [defaults integerForKey:@"value"];
NSString *valueString = [NSString stringWithFormat:@"%i",value];
// Update the UI elements with the saved data
valueTextField.text = valueString;
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)save:(id)sender {
[valueTextField resignFirstResponder];
int value = [[valueTextField text] integerValue];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:value forKey:@"value"];
[defaults synchronize];
NSLog(@"Data saved");
}
@end
NextViewController.h:
#import <UIKit/UIKit.h>
@class ViewController;
@interface NextViewController : UIViewController
@end
NextViewController.m:
#import "NextViewController.h"
#import "ViewController.h"
@interface NextViewController ()
@end
@implementation NextViewController
-(IBAction)displayClicks:(id)sender
{
if(value<20)
{
self.view.backgroundColor = [UIColor redColor];
}
else {
self.view.backgroundColor = [UIColor greenColor];
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end