0

我试图使在文本字段中输入的值更改下一个 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
4

1 回答 1

0

起初它毕竟不是调用父方法的好点。

- (void)viewDidLoad
{

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

// 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;

}

在第二个视图控制器中,您从 UserDefaluts 读取“值”的值?

-(IBAction)displayClicks:(id)sender
{
if(value<20)
{
    self.view.backgroundColor = [UIColor redColor];
}
else {
    self.view.backgroundColor = [UIColor greenColor];
}

}

if(value<20) 你从哪里拿?也许你以前吃过它?

   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    int value = [defaults integerForKey:@"value"];
于 2012-11-09T07:32:05.533 回答