In the start screen of my app you are able to choose language between English and Swedish by clicking on either the flag of UK or Sweden.
The problem is that the ViewDidLoad does not recognize changes in the NSUserDefaults when you click a button. But when you restart the app, the language is the latest flag you clicked! So it saves the NSUserDefault but it only loads it the first time in ViewDidLoad..
When you click the English flag, sprakval sets to 0, and if you click the swedish flag, sprakval sets to 1. When you click a flag, it changes to a image with a tick icon in front of the flag.
Code:
-(IBAction) sprakEN
{
sprakval=0;
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
[sprakvalet setInteger:sprakval forKey:#"Sprak "];
[sprakvalet synchronize];
[super viewDidLoad];
}
-(IBAction) sprakSE
{
sprakval=1;
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
[sprakvalet setInteger:sprakval forKey:#"Sprak "];
[sprakvalet synchronize];
[super viewDidLoad];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
sprakval2 = [sprakvalet integerForKey:#"Sprak "];
if (sprakval2==0)
{
spraklabel.text = [NSString stringWithFormat:#"Language:"];
[lhb setTitle:#"english" forState:UIControlStateNormal];
[hlb setTitle:#"english" forState:UIControlStateNormal];
[fhb setTitle:#"english." forState:UIControlStateNormal];
[blandatb setTitle:#"english.." forState:UIControlStateNormal];
UIImage *encheck = [UIImage imageNamed:#"United_Kingdomchecked.png"];
[enbutton setImage:encheck forState:UIControlStateNormal];
UIImage *seuncheck = [UIImage imageNamed:#"Sweden.png"];
[sebutton setImage:seuncheck forState:UIControlStateNormal];
self.title = #"Game";
}
else if(sprakval2==1)
{
spraklabel.text = [NSString stringWithFormat:#"Språk:"];
[lhb setTitle:#"swedish" forState:UIControlStateNormal];
[hlb setTitle:#"swedish" forState:UIControlStateNormal];
[flb setTitle:#"swedish" forState:UIControlStateNormal];
[fhb setTitle:#"swedish" forState:UIControlStateNormal];
[blandatb setTitle:#"swedish" forState:UIControlStateNormal];
self.title = #"Spel";
UIImage *secheck = [UIImage imageNamed:#"Swedenchecked.png"];
[sebutton setImage:secheck forState:UIControlStateNormal];
UIImage *enuncheck = [UIImage imageNamed:#"United_Kingdom.png"];
[enbutton setImage:enuncheck forState:UIControlStateNormal];
}
// Do any additional setup after loading the view, typically from a nib.
}
This is because you are calling ViewDidload method through its super class in -(IBAction) sprakSE
and -(IBAction) sprakEN
methods. So replace
[super viewDidLoad]; with
[self viewDidLoad]; in both methods. It will work properly.
Hope it helps you.
viewDidLoad is a method invoked after view has been loaded from nib file. You are not supposed to call it manually.
If you have written the code to refresh the controls in viewDidLoad move that into a different method and invoke that method from your button event handler.
- (void)adjustControlsForLanguage
{
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
sprakval2 = [sprakvalet integerForKey:#"Sprak "];
if (sprakval2==0)
{
spraklabel.text = [NSString stringWithFormat:#"Language:"];
[lhb setTitle:#"english" forState:UIControlStateNormal];
[hlb setTitle:#"english" forState:UIControlStateNormal];
[fhb setTitle:#"english." forState:UIControlStateNormal];
[blandatb setTitle:#"english.." forState:UIControlStateNormal];
UIImage *encheck = [UIImage imageNamed:#"United_Kingdomchecked.png"];
[enbutton setImage:encheck forState:UIControlStateNormal];
UIImage *seuncheck = [UIImage imageNamed:#"Sweden.png"];
[sebutton setImage:seuncheck forState:UIControlStateNormal];
self.title = #"Game";
}
else if(sprakval2==1)
{
spraklabel.text = [NSString stringWithFormat:#"Språk:"];
[lhb setTitle:#"swedish" forState:UIControlStateNormal];
[hlb setTitle:#"swedish" forState:UIControlStateNormal];
[flb setTitle:#"swedish" forState:UIControlStateNormal];
[fhb setTitle:#"swedish" forState:UIControlStateNormal];
[blandatb setTitle:#"swedish" forState:UIControlStateNormal];
self.title = #"Spel";
UIImage *secheck = [UIImage imageNamed:#"Swedenchecked.png"];
[sebutton setImage:secheck forState:UIControlStateNormal];
UIImage *enuncheck = [UIImage imageNamed:#"United_Kingdom.png"];
[enbutton setImage:enuncheck forState:UIControlStateNormal];
}
}
viewDidLoad
- (void)viewDidLoad{
[super viewDidLoad];
[self adjustControlsForLanguage];
}
Button Event Handlers
-(IBAction) sprakEN {
sprakval=0;
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
[sprakvalet setInteger:sprakval forKey:#"Sprak "];
[sprakvalet synchronize];
[self adjustControlsForLanguage];
}
-(IBAction) sprakSE {
sprakval=1;
NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
[sprakvalet setInteger:sprakval forKey:#"Sprak "];
[sprakvalet synchronize];
[self adjustControlsForLanguage];
}
EDIT : Since you are using tabBar based app, it's better to use the viewWillAppear to reload the language specific controls
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self adjustControlsForLanguage];
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
Related
i saved results from API to nsmutabledictionary. In this API is paging after 15 results (1,2,3, etc).
I need to fill resultDictionary with results from API.
My code:
self.resultDictionary = [[NSDictionary alloc] init];
self.resultDictionary = [self.api sendDataViaPostAndFormDataWithTwoParameters:#"email" with:[[NSUserDefaults standardUserDefaults] valueForKey:#"email"] parameterTwo:#"heslo" with:[[NSUserDefaults standardUserDefaults] valueForKey:#"heslo"] onUrl:[NSString stringWithFormat:#"http://***", [[NSUserDefaults standardUserDefaults] valueForKey:#"id"], [[NSUserDefaults standardUserDefaults] valueForKey:#"token"], page] withMethod:#"POST" success:^(BOOL success) {
} failure:^(NSString *fail) {
NSLog(#"%#", fail);
}];
It works fine - it shows 15 results. But, when i scroll down in tableview and after 15 index load next page in api, it shows next 15 results. I need to join both (30results / old and new).
I tried add entries... but no effect.
Could you help me please?
edit:
my rest of code with edit from Ashish
#implementation testingTableViewController {
NSMutableDictionary * resultDictionary;
}
-(void)reloadData:(int)page {
// set selected NO
if ([[NSUserDefaults standardUserDefaults] valueForKey:#"id"] == NULL) {
loginViewController *login = [[loginViewController alloc] init];
login.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:login animated:NO];
} else {
SHOW_NAVIGATION_BAR
self.api = [[API alloc] init];
self.temp = [self.api sendDataViaPostAndFormDataWithTwoParameters:#"email" with:[[NSUserDefaults standardUserDefaults] valueForKey:#"email"] parameterTwo:#"heslo" with:[[NSUserDefaults standardUserDefaults] valueForKey:#"heslo"] onUrl:[NSString stringWithFormat:#"http://*****/=&page=%d", [[NSUserDefaults standardUserDefaults] valueForKey:#"id"], [[NSUserDefaults standardUserDefaults] valueForKey:#"token"], page] withMethod:#"POST" success:^(BOOL success) {
NSLog(#"OK načteno");
} failure:^(NSString *fail) {
NSLog(#"%#", fail);
}];
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
resultDictionary = [NSMutableDictionary dictionary];
self.temp = [[NSDictionary alloc] init];
[self reloadData:1];
[self.tableView reloadData];
[self.tableView setNeedsLayout];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:#"cell"];
self.chatButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.commentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton *commentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
commentButton.frame = CGRectMake(15, 0, 20, 20);
[commentButton setImage:[UIImage imageNamed:#"chat"] forState:UIControlStateNormal];
[commentButton addTarget:self action:#selector(page1) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:commentButton];
UIButton *chatButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
chatButton.frame = CGRectMake(65, 0, 20, 20);
[chatButton setImage:[UIImage imageNamed:#"like"] forState:UIControlStateNormal];
[chatButton addTarget:self action:#selector(page2) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:chatButton];
}
-(void)page1 {
[self reloadData:1];
[resultDictionary addEntriesFromDictionary:self.temp];
[self.tableView reloadData];
}
-(void)page2 {
[self reloadData:2];
[resultDictionary addEntriesFromDictionary:self.temp];
[self.tableView reloadData];
}
When click at first button, result is 15, if i again click on first button, result is still 15 instead 30
Thank you for any response
As per your code
self.resultDictionary = [[NSDictionary alloc] init];
self.resultDictionary = [self.api sendDataViaPostAndFormDataWithTwoParameters:#"email" with:[[NSUserDefaults standardUserDefaults] valueForKey:#"email"] parameterTwo:#"heslo" with:[[NSUserDefaults standardUserDefaults] valueForKey:#"heslo"] onUrl:[NSString stringWithFormat:#"http://***", [[NSUserDefaults standardUserDefaults] valueForKey:#"id"], [[NSUserDefaults standardUserDefaults] valueForKey:#"token"], page] withMethod:#"POST" success:^(BOOL success) {
} failure:^(NSString *fail) {
NSLog(#"%#", fail);
}];
You are not using NSMutableDictionary. Create instance of NSMutableDictionary at top of the class.
NSMutableDictionary * resultDictionary;
Initialize it in viewDidLoad method
self.resultDictionary = [NSMutableDictionary dictionary];
Finally in your code for fetching result form server.
NSDictionary *tempDict = [self.api sendDataViaPostAndFormDataWithTwoParameters:#"email" with:[[NSUserDefaults standardUserDefaults] valueForKey:#"email"] parameterTwo:#"heslo" with:[[NSUserDefaults standardUserDefaults] valueForKey:#"heslo"] onUrl:[NSString stringWithFormat:#"http://***", [[NSUserDefaults standardUserDefaults] valueForKey:#"id"], [[NSUserDefaults standardUserDefaults] valueForKey:#"token"], page] withMethod:#"POST" success:^(BOOL success) {
[self.resultDictionary addEntriesFromDictionary:tempDict];
} failure:^(NSString *fail) {
NSLog(#"%#", fail);
}];
I've created a button that stops and plays background music when clicked. It works great, but when I click on the home button, and relaunch the application (background - foreground) the button doesn't work. I click on it and it does nothing. Help please!! Thanks
This is the code:
- (IBAction)muteButtonPressed:(id)sender {
UIImage *currentImage = [self.muteButton currentImage];
UIImage *vol1 = [UIImage imageNamed:#"Volume 1"];
UIImage *vol2 = [UIImage imageNamed:#"Volume 2"];
if ([currentImage isEqual:vol1]) {
[self.muteButton setImage:vol2 forState:UIControlStateNormal];
[self.backgroundMusic stop];
self.scene.playSounds = NO;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:0 forKey:#"playSounds"];
[defaults synchronize];
}
if ([currentImage isEqual:vol2]) {
[self.muteButton setImage:vol1 forState:UIControlStateNormal];
[self playBackground];
self.scene.playSounds = YES;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:1 forKey:#"playSounds"];
[defaults synchronize];
}
}
and this is the code in the viewcontroller :
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *playSoundsString = [defaults objectForKey:#"playSounds"];
NSInteger playSoundsInt = [playSoundsString intValue];
NSNumber *playSoundsNumber = [NSNumber numberWithInteger:playSoundsInt];
self.scene.playSounds = [playSoundsNumber boolValue];
if (self.scene.playSounds == YES) {
UIImage *vol1 = [UIImage imageNamed:#"Volume 1"];
self.scene.playSounds = YES;
[self playBackground];
[self.muteButton setImage:vol1 forState:UIControlStateNormal];
}
else if (self.scene.playSounds == NO) {
UIImage *vol2 = [UIImage imageNamed:#"Volume 2"];
self.scene.playSounds = NO;
[self.muteButton setImage:vol2 forState:UIControlStateNormal];
}
finally this is when my app enters background (in viewcontroller) :
if (self.scene.playSounds == YES) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(stopMusic:) name:#"SOUND_OFF" object:nil];
}
I am using onegray's Radio button class in one of my projects. the one mentioned here: Best radio-button implementation for IOS
I am using these radio buttons for my answer choices on a quiz. when the user clicks the next button, the labels are populated with new choices. the only problem is that the old ones dont disappear. So when I click next, the new set of buttons are placed on top of the old ones.
what is the simplest way to first check to see if they already exist.. and if so.. delete them.. before displaying the new ones?
here is my code.
#interface LABViewControllerQuiz ()
#end
#implementation LABViewControllerQuiz
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
int counter =0;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
_fileContents = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"quizQuestions" ofType:#"txt"] encoding:NSUTF8StringEncoding error: nil];
_theScanner = [NSScanner scannerWithString:_fileContents];
_separator = [NSCharacterSet characterSetWithCharactersInString:#"~"];
_lineBreak =[NSCharacterSet characterSetWithCharactersInString:#"#"];
_alreadyGeneratedNumbers =[[NSMutableArray alloc]init];
_numQuestions =0;
_userAnswers = [[NSMutableArray alloc]init];
_answerKey = [[NSMutableArray alloc]init];
[self nextQuestion:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)nextQuestion:(UIButton *)sender
{
_NextQuestionButton.enabled = YES;
_submitButton.enabled = NO;
NSLog(#"NumQuestion = %d", _numQuestions);
if (_numQuestions >9)
{
_NextQuestionButton.enabled = NO;
_submitButton.enabled = YES;
}else
{
int r = arc4random() %20;
while ([_alreadyGeneratedNumbers containsObject:[NSNumber numberWithInt:r]])
{
r = arc4random() %20;
}
[_alreadyGeneratedNumbers addObject:[NSNumber numberWithInt:r]];
while(![_theScanner isAtEnd])
{
NSLog(#"Location= %d", [_theScanner scanLocation]);
NSLog(#"Already Generated numbers:");
int i =0;
while (i < [_alreadyGeneratedNumbers count])
{
NSLog(#"%#", [_alreadyGeneratedNumbers objectAtIndex:i]);
i++;
}
NSString *line;
_lineArray = [[NSMutableArray alloc] init];
[_theScanner scanUpToCharactersFromSet:_lineBreak intoString:&line];
[_theScanner setCharactersToBeSkipped:_lineBreak];
NSScanner *inner = [NSScanner scannerWithString:line];
NSString *word;
int wordCount = 0;
NSLog(#"r = %d counter = %d", r, counter);
if (counter ==r)
{
while(![inner isAtEnd])
{
[inner scanUpToCharactersFromSet:_separator intoString:&word];
[inner setCharactersToBeSkipped:_separator];
[_lineArray insertObject:word atIndex:wordCount];
_questionText.text = [NSString stringWithFormat:#"Question %d \n %#", _numQuestions +1,[_lineArray objectAtIndex:0]];
wordCount++;
[_theScanner setScanLocation:0];
counter = 0;
}
[sender setHidden:YES];
NSMutableArray* buttons = [NSMutableArray arrayWithCapacity:4];
CGRect btnRect = CGRectMake(25, 420, 300, 30);
for (NSString* optionTitle in #[[_lineArray objectAtIndex:1], [_lineArray objectAtIndex:2], [_lineArray objectAtIndex:3], [_lineArray objectAtIndex:4]])
{
RadioButton* btn = [[RadioButton alloc] initWithFrame:btnRect];
[btn addTarget:self action:#selector(onRadioButtonValueChanged:) forControlEvents:UIControlEventValueChanged];
btnRect.origin.y += 40;
[btn setTitle:optionTitle forState:UIControlStateNormal];
[btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
[btn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateSelected];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
[self.view addSubview:btn];
[buttons addObject:btn];
}
[buttons[0] setGroupButtons:buttons]; // Setting buttons into the group
[buttons[0] setSelected:NO]; // Making the first button initially selected
NSLog(#"the question is = %#", [_lineArray objectAtIndex:0]);
//NSLog(#"Line arrayINDEX %d = %#", wordCount,[_lineArray objectAtIndex:wordCount]); _numQuestions ++;
break;
}else
{
counter ++;
}
}
}
[_answerKey addObject:[_lineArray objectAtIndex:5]];
}
-(void) onRadioButtonValueChanged:(RadioButton*)sender
{
// Lets handle ValueChanged event only for selected button, and ignore for deselected
if(sender.selected)
{
NSLog(#"Selected: %#", sender.titleLabel.text);
}
}
Save buttons as an instance variable. You're already adding all your buttons into the array, you just throw the array out for some reason.
#interface LABViewControllerQuiz ()
#property (strong) NSMutableArray *buttons;
#end
And then this line:
NSMutableArray* buttons = [NSMutableArray arrayWithCapacity:4];
Becomes these lines:
if (self.buttons) {
[self.buttons makeObjectsPerformSelector:#selector(removeFromSuperview)];
[self.buttons removeAllObjects];
} else {
self.buttons = [NSMutableArray arrayWithCapacity:4];
}
I saw a couple of examples but I cannot figure out what's going wrong when trying to save my text field input and reload it when restarting the app.
I have something like this in my .m file (.h file only has a <UITextViewDelegate>);
#implementation C4WorkSpace{
UITextView *textField;
C4Button *okButton;
C4Label *savedText;
}
-(void)setup {
//add text field
CGRect textViewFrame = CGRectMake(20.0f, 20, self.canvas.width-40, 124.0f);
textField = [[UITextView alloc] initWithFrame:textViewFrame];
textField.returnKeyType = UIReturnKeyDone;
[textField becomeFirstResponder];
textField.delegate = self;
//textField.hidden=true;
[self.view addSubview:textField];
okButton=[C4Button buttonWithType:ROUNDEDRECT];
[okButton setTitle:#"Save" forState:NORMAL];
okButton.center=self.canvas.center;
[self.canvas addUIElement:okButton];
[okButton runMethod:#"saveDefault" target:self forEvent:TOUCHUPINSIDE];
savedText=[C4Label labelWithText:#"default"];
savedText.center=CGPointMake(self.canvas.center.x, self.canvas.center.y+40);
[self.canvas addLabel:savedText];
}
-(void)saveDefault{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:textField.text forKey:#"userName"];
[defaults synchronize];
C4Log(#"defaults: %#",defaults);
C4Log(#"defaults: %#", [defaults objectForKey:#"userName"]);
savedText.text=textField.text;
}
-(void)viewDidLoad{
NSMutableString *text=[[NSUserDefaults standardUserDefaults] objectForKey:#"userName"];
C4Log(#"loadedText:%s", text);
textField.text=text;
savedText.text=text;
}
#end
I'm not sure what exactly is going wrong, but when I restart the app the loadedText is always: "¯8*:å". Doesn't matter what I saved.
I found the easiest solution is to set in
ViewDidLoad
text=[[NSUserDefaults standardUserDefaults] objectForKey:#"userName"];
and in setup
if (text!=nil) {
textField.text=text;
}
Where does Setup method is call ? I think in viewDidLoad you initialize, but setup method called earlier.
You don't save this info,so button don't recognizer or load info and set text before initialization.
in setup method load info
UItextView *k = [UItextView alloc] init];
k.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"userName"];
and take a look what will be.
UPDATE:
That's wrong;
[c4workspace loadInfoFromDefaults];
[c4workspace alloc]init]; (calls viedidload method with load info)
You need
[c4workspace alloc]init];
[c4workspace loadInfoFromDefaults];
Please post code where you create c4WorkSpace object.
UPDATE 2:
-(void)setup {
//add text field
CGRect textViewFrame = CGRectMake(20.0f, 20, self.canvas.width-40, 124.0f);
textField = [[UITextView alloc] initWithFrame:textViewFrame];
textField.returnKeyType = UIReturnKeyDone;
[textField becomeFirstResponder];
textField.delegate = self;
//textField.hidden=true;
[self.view addSubview:textField];
okButton=[C4Button buttonWithType:ROUNDEDRECT];
[okButton setTitle:#"Save" forState:NORMAL];
okButton.center=self.canvas.center;
[self.canvas addUIElement:okButton];
[okButton runMethod:#"saveDefault" target:self forEvent:TOUCHUPINSIDE];
savedText=[C4Label labelWithText:#"default"];
savedText.center=CGPointMake(self.canvas.center.x, self.canvas.center.y+40);
[self.canvas addLabel:savedText];
}
- (void) setTextView
{
textField.text=[[NSUserDefaults standardUserDefaults] objectForKey:#"userName"];
savedText.text=[[NSUserDefaults standardUserDefaults] objectForKey:#"userName"];
}
So you call this like:
C4WorkSpace *c4 = [C4WorkSpace alloc] init];
[c4 setup]
[c4 setTextView];
I have three text fields: first name, last name, and age, also a photo. What can I do so that the information saves automatically, so that i dont have to click a button?
This is my 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
This is my 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];
}
you will have to work with the <UITextFieldDelegate> protocol
Reference: UITextFieldDelegate Protocol
you will have to set
textField.delegate = yourViewController
and can then work with the protocol functions, that handle input and character changing of your textview.
for example you cound use
- (BOOL)textFieldShouldReturn:(UITextField *)textField
to save the textfield content when the user presses the return button =)
EDIT: probably this method is better suited for your needs - i was a bit tired yesterday when writing the post =)
- (void)textFieldDidEndEditing:(UITextField *)textField {
//save your textfied.text string here :)
}
You need to set the delegate of the UITextfield to the view controller in your viewDidLoad method like
firstNameTextField.delegate = self;
lastNameTextField.delegate = self;
ageTextField.delegate = self;
Your view controller needs to implement the UITextFieldDelegate Protocol method:
- (void)textFieldDidEndEditing:(UITextField *)textField {
//Do save Operations here
}
This will save only after the text is done editing. If you want to save as the user is typing, use
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *stringToSave=[textField.text stringByReplacingCharactersInRange:range withString:string];
//Identify text field by comparing textField with you text fields and do save operations
return YES;
}