我有三个文本字段:名字、姓氏和年龄,还有一张照片。我该怎么做才能自动保存信息,这样我就不必单击按钮?
这是我的ViewController.h
:
#import <UIKit/UIKit.h>
@interface ContactViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
IBOutlet UIImageView *contactImageView;
IBOutlet UITextField *firstNameTextField;
IBOutlet UITextField *lastNameTextField;
IBOutlet UITextField *ageTextField;
}
- (IBAction)save:(id)sender;
- (IBAction)chooseImage:(id)sender;
@end
这是我的ViewController.m
:
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *frontName = [defaults objectForKey:@"firstname"];
NSString *lastName = [defaults objectForKey:@"lastname"];
int age = [defaults integerForKey:@"age"];
NSString *ageString = [NSString stringWithFormat:@"%i",age];
NSData *imageData = [defaults dataForKey:@"image"];
UIImage *contactImage = [UIImage imageWithData:imageData];
firstNameTextField.text = frontName;
lastNameTextField.text = lastName;
ageTextField.text = ageString;
contactImageView.image = contactImage;
}
- (void)viewDidUnload {
[contactImageView release];
contactImageView = nil;
[firstNameTextField release];
firstNameTextField = nil;
[lastNameTextField release];
lastNameTextField = nil;
[ageTextField release];
ageTextField = nil;
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)save:(id)sender {
[firstNameTextField resignFirstResponder];
[lastNameTextField resignFirstResponder];
[ageTextField resignFirstResponder];
// Create strings and integer to store the text info
NSString *frontName = [firstNameTextField text];
NSString *lastName = [lastNameTextField text];
int age = [[ageTextField text] integerValue];
UIImage *contactImage = contactImageView.image;
NSData *imageData = UIImageJPEGRepresentation(contactImage, 100);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:frontName forKey:@"firstname"];
[defaults setObject:lastName forKey:@"lastname"];
[defaults setInteger:age forKey:@"age"];
[defaults setObject:imageData forKey:@"image"];
[defaults synchronize];
NSLog(@"Data saved");
}
- (IBAction)chooseImage:(id)sender {
UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
contactImageView.image = image;
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissModalViewControllerAnimated:YES];
}