I got a UITextField as subview.
- (void)viewDidLoad {
[super viewDidLoad];
textField = [[UITextField alloc] initWithFrame:CGRectMake(21, 21, 159, 37)];
textField.borderStyle = UITextBorderStyleNone;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = #"name";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.textColor = [UIColor whiteColor];
textField.keyboardAppearance = UIKeyboardAppearanceDark;
textField.delegate = (id) self;
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
[textField addTarget:self action:#selector(saveData:) forControlEvents:UIControlEventEditingDidEnd];
[self.view addSubview:textField];
}
-(void)saveData:(id)sender {
NSString *savestring = textField.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestring forKey:#"savedstring"];
[defaults synchronize];
}
To load the data (viewDidLoad)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedstring"];
[textField setText:loadstring];
Now the problem is that it doesn't save and load the text of the UITextField.
First you need to enter some string in the Textfield and press return key, so that it will get a chance to call your "saveData" method and store the value in the NSUserDefaults. Just check all the values.
I found a solution:
textField.text = [defaults objectForKey:#"savedstring"];
Thanks everyone for your answers
"addSubview" after this method write to load the data method...
[self.view addSubview:textField];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedstring"];
[textField setText:loadstring];
Related
When my UITextView places a line of text into my first UITextField i cant save the text it holds.
Heres my code, this is to move the information from a textview
-(IBAction)print:(id)sender {
NSLog(#"text = %#",[textView text] );
NSArray *textArray = [[textView text] componentsSeparatedByString:#"\n"];
if (textArray.count > 0) {
NSString *line1 = textArray[0];
[myTextField setText:line1];
if (textArray.count > 1) {
NSString *line2 = textArray[1];
[myTextField1 setText:line2];
}
}
[textView setText:#""];
[textView resignFirstResponder];
}
Heres how i am currently trying to save and load the information.
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[myTextField setText:[defaults valueForKey:#"textfield_text"]];
[myTextField setDelegate:self];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *defaultsKeyForTextField;
if ([textField isEqual:myTextField]) {
defaultsKeyForTextField = #"textfield_text";
}
[defaults setValue:textField.text forKey:defaultsKeyForTextField];
[defaults synchronize];
}
What seems to happen is that the text only saves when i enter in text manually.
As user TangZijian pointed out, textFieldDidEndEditing will be called when the textfield resigns first responder.
None of your code in print function do this.
Since set textfield as first responder and immediately resign it seems like a bad idea, you can move the code in textFieldDidEndEditing to print.
-(IBAction)print:(id)sender {
NSLog(#"text = %#",[textView text] );
NSArray *textArray = [[textView text] componentsSeparatedByString:#"\n"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *defaultsKeyForTextField;
if (textArray.count > 0) {
NSString *line1 = textArray[0];
[myTextField setText:line1];
defaultsKeyForTextField = #"textfield_text";
[defaults setValue:textField.text forKey:defaultsKeyForTextField];
[defaults synchronize];
if (textArray.count > 1) {
NSString *line2 = textArray[1];
[myTextField1 setText:line2];
}
}
[textView setText:#""];
[textView resignFirstResponder];
}
I think you should be using a the Editing Changed event to detect changes to your text fields value. Put this in your viewDidLoad method.
[myTextField addTarget:self
action:#selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
Then change your code to:
- (void)textFieldDidChange:(UITextField *)textField {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *defaultsKeyForTextField;
if ([textField isEqual:myTextField]) {
defaultsKeyForTextField = #"textfield_text";
}
[defaults setValue:textField.text forKey:defaultsKeyForTextField];
[defaults synchronize];
}
In my .xib file I have a button that when pressed generates 3 UITextFields. These text fields each have a tag so they are declared independently. My problem is that I want to save these text fields using NSUserDefaults and I'm not sure how to do that. I have been able to write out everything using no loops but if I could do it with loops and tags I would be very happy. I'm just not sure if I can use tags or really how to do it at all.
I've been able to create the text fields with an if statement(to make a limit on how many can be created) when the button is pressed but beyond that I am not sure. Here is what I have so far...
int y = 115; // For height of buttons in addClass
int i = 1; // Counter
- (IBAction)addClass:(id)sender
{
if (i < 8) {
UITextField *class = [[UITextField alloc] initWithFrame:CGRectMake(20, y, 118, 30)];
class.tag = i;
class.placeholder = #"Class";
class.borderStyle = UITextBorderStyleRoundedRect;
class.font = [UIFont fontWithName:#"System" size:14.0];
class.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:class];
UITextField *grade = [[UITextField alloc] initWithFrame:CGRectMake(169, y, 59, 30)];
grade.tag = i;
grade.placeholder = #"Grade";
grade.borderStyle = UITextBorderStyleRoundedRect;
grade.font = [UIFont fontWithName:#"System" size:14.0];
grade.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:grade];
UITextField *credit = [[UITextField alloc] initWithFrame:CGRectMake(236, y, 64, 30)];
credit.tag = i;
credit.placeholder = #"Credits";
credit.borderStyle = UITextBorderStyleRoundedRect;
credit.font = [UIFont fontWithName:#"System" size:14.0];
credit.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:credit];
y = y + 45;
i++;
}}
- (IBAction)save:(id)sender
{
//Grade1 save string
NSString *saveString0 = grade1.text;
NSUserDefaults *defaults0 = [NSUserDefaults standardUserDefaults];
[defaults0 setObject:saveString0 forKey:#"saveString0"];
[defaults0 synchronize];
//Grade2 save string
NSString *saveString1 = grade2.text;
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 setObject:saveString1 forKey:#"saveString1"];
[defaults1 synchronize];
//Grade3 save string
NSString *saveString2 = grade3.text;
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
[defaults2 setObject:saveString2 forKey:#"saveString2"];
[defaults2 synchronize];
...
}
As you can see save string for the grades are all individually coded. What I would like to learn how to do is create a for loop and the expression will go up to the value of i(the counter) so something like...
for(int j = 0; j <= i; j++)
and then j is the value that would go into the *saveString, *defaults, and grade.text.
If anyone knows how to do this or has a better solution I would be very grateful.
Thanks pedros. One last thing, if I have...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadString = [defaults objectForKey:#"saveString"];
[grade1 setText:loadString];
[loaded setText:#"Data Loaded Successfully."];
How would I change that to implement the for loop as well?
Try something like this.
NSArray *grades = #[grade1, grade2, grade3, ...];
for(int j = 0; j <= i; j++) {
NSString *saveString = [(UITextField*)grades[j] text];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *key = [NSString stringWithFormat:#"saveString%d", j];
[defaults setObject:saveString forKey:key];
}
[defaults synchronize];
Second part would be really similar.
NSArray *grades = #[grade1, grade2, grade3, ...];
for(int j = 0; j <= i; j++) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadString = [defaults objectForKey:#"saveString%d", j];
[(UITextField*)grades[j] setText:loadString];
}
[loaded setText:#"Data Loaded Successfully."];
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];
This question already has answers here:
How to store custom objects in NSUserDefaults
(7 answers)
Closed 8 years ago.
In my app I let users to pick a colour of background, tint and text. How can I save this settings after the app is closed? I mean when user again starts the app he wants to see the background, tint and text colour from previous usage.
This is how I have set the colours.
self.BackgroundView.backgroundColor = [UIColor colorWithRed:248.0/255.0 green:242.0/255.0 blue:229.0/255.0 alpha:1.0];
[[[self navigationController] navigationBar] setTintColor:[UIColor colorWithRed:103.0/255.0 green:10.0/255.0 blue:10.0/255.0 alpha:1.0]];
self.QuoteText.textColor = [UIColor colorWithRed:131.0/255.0 green:21.0/255.0 blue:21.0/255.0 alpha:1.0];
Trying to solve by following Greg's (probably the right) answer gives SIGABRT error by clicking on following button:
- (IBAction)setcolor:(id)sender {
UIColor *backgroundColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:220.0/255.0 alpha:1.0];
self.BackgroundView.backgroundColor = backgroundColor;
UIColor *tintColor = [UIColor colorWithRed:129.0/255.0 green:165.0/255.0 blue:148.0/255.0 alpha:1.0];
[[[self navigationController] navigationBar] setTintColor:tintColor];
UIColor *textColor = [UIColor colorWithRed:0.0/255.0 green:98.0/255.0 blue:139.0/255.0 alpha:1.0];
self.QuoteText.textColor = textColor;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:backgroundColor forKey:#"BACKGCOLOR"];
[defaults setObject:tintColor forKey:#"TINTCOLOR"];
[defaults setObject:textColor forKey:#"TEXTCOLOR"];
[defaults synchronize];
}
If user pick up colour instead of
self.BackgroundView.backgroundColor = [UIColor colorWithRed:248.0/255.0 green:242.0/255.0 blue:229.0/255.0 alpha:1.0];
You can do
UIColor *backgroundColor = [UIColor colorWithRed:248.0/255.0 green:242.0/255.0 blue:229.0/255.0 alpha:1.0];
self.BackgroundView.backgroundColor = backgroundColor;
NSData *backgroundColorData = [NSKeyedArchiver archivedDataWithRootObject:backgroundColor];
UIColor *tintColor = [UIColor colorWithRed:103.0/255.0 green:10.0/255.0 blue:10.0/255.0 alpha:1.0];
[[[self navigationController] navigationBar] setTintColor:tintColor];
NSData *tintColorData = [NSKeyedArchiver archivedDataWithRootObject: tintColor];
UIColor *textColor = [UIColor colorWithRed:131.0/255.0 green:21.0/255.0 blue:21.0/255.0 alpha:1.0];
self.QuoteText.textColor = textColor;
NSData *textColorData = [NSKeyedArchiver archivedDataWithRootObject: textColor];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: backgroundColorData forKey:#"BACKGCOLOR"];
[defaults setObject:tintColorData forKey:#"TINTCOLOR"];
[defaults setObject:textColorData forKey:#"TEXTCOLOR"];
[defaults synchronize];
You do the same for tint and text colour (just use different key).
In the view controller where you want to change your view colour in viewDidLoad you do:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *backgColorData = [defaults objectForKey:#"BACKGCOLOR"];
UIColor *backgColor = [NSKeyedUnarchiver unarchiveObjectWithData:backgColorData];
NSData *tintColorData = [defaults objectForKey:#"TINTCOLOR"];
UIColor *tintColor = [NSKeyedUnarchiver unarchiveObjectWithData:tintColorData];
NSData *textColorData = [defaults objectForKey:#"TEXTCOLOR"];
UIColor *textColor = [NSKeyedUnarchiver unarchiveObjectWithData: textColorData];
if (backgColor)
self.BackgroundView.backgroundColor = backgColor;
if (tintColor)
[[[self navigationController] navigationBar] setTintColor:tintColor];
if (textColor)
self.QuoteText.textColor = textColor;
Apple is providing the NSUserDefaults for this, it does act like the preferences for your user / application. Example taken from here
Saving :
NSString *valueToSave = #"someValue";
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"preferenceName"];
To get it back later :
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"preferenceName"];
Test using nsuserdefaults to save the settings or, write to a plist.
I have a big problem and could not solve it for few days already.
When app loads at first time, I'm saving 4 colors to NSUserDeafaults in first UIViewController.
ViewController.m
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSUserDefaults *sharedDefaults = [NSUserDefaults standardUserDefaults];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger countValue = [defaults integerForKey:#"Array"];
if ([sharedDefaults boolForKey:#"FirstLaunch"])
{
[self openSubView];
[sharedDefaults setBool:NO forKey:#"FirstLaunch"];
[sharedDefaults synchronize];
[self saveColorsToDefaults];
// [prefs synchronize];
} // Do any additional setup after loading the view.
else if(countValue == 1)
{
}
}
-(void)saveColorsToDefaults{
const CGFloat *components1 = CGColorGetComponents([UIColor darkGrayColor].CGColor);
const CGFloat *components2 = CGColorGetComponents([UIColor blueColor].CGColor);
const CGFloat *components3 = CGColorGetComponents([UIColor redColor].CGColor);
const CGFloat *components4 = CGColorGetComponents([UIColor purpleColor].CGColor);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setFloat:components1[0] forKey:#"cr"];
[prefs setFloat:components1[1] forKey:#"cg"];
[prefs setFloat:components1[2] forKey:#"cb"];
[prefs setFloat:components1[3] forKey:#"ca"];
[prefs setFloat:components2[0] forKey:#"cr2"];
[prefs setFloat:components2[1] forKey:#"cg2"];
[prefs setFloat:components2[2] forKey:#"cb2"];
[prefs setFloat:components2[3] forKey:#"ca2"];
[prefs setFloat:components3[0] forKey:#"cr3"];
[prefs setFloat:components3[1] forKey:#"cg3"];
[prefs setFloat:components3[2] forKey:#"cb3"];
[prefs setFloat:components3[3] forKey:#"ca3"];
[prefs setFloat:components4[0] forKey:#"cr4"];
[prefs setFloat:components4[1] forKey:#"cg4"];
[prefs setFloat:components4[2] forKey:#"cb4"];
[prefs setFloat:components4[3] forKey:#"ca4"];
[prefs synchronize];
NSLog(#"I just saved colors");
}
And after I need to set these colors to `DrawViewControllers drawing instruments.
I can get only last 3 colors but 1st color does not apears.
But when I set color for 1st instrument via colorPicker and save all the colors again to NSUserDefaults it works great!
-(void)LoadColorsAtStart
{
NSUserDefaults *prefers = [NSUserDefaults standardUserDefaults];
UIColor* tColor = [UIColor colorWithRed:[prefers floatForKey:#"cr"] green:[prefers floatForKey:#"cg"] blue:[prefers floatForKey:#"cb"] alpha:[prefers floatForKey:#"ca"]];
UIColor* tColor2 = [UIColor colorWithRed:[prefers floatForKey:#"cr2"] green:[prefers floatForKey:#"cg2"] blue:[prefers floatForKey:#"cb2"] alpha:[prefers floatForKey:#"ca2"]];
UIColor* tColor3 = [UIColor colorWithRed:[prefers floatForKey:#"cr3"] green:[prefers floatForKey:#"cg3"] blue:[prefers floatForKey:#"cb3"] alpha:[prefers floatForKey:#"ca3"]];
UIColor* tColor4 = [UIColor colorWithRed:[prefers floatForKey:#"cr4"] green:[prefers floatForKey:#"cg4"] blue:[prefers floatForKey:#"cb4"] alpha:[prefers floatForKey:#"ca4"]];
[prefers synchronize];
[self extractRGBforBlack:tColor];
[self extractRGBforBlue:tColor2];
[self extractRGBforRed:tColor3];
[self extractRGBforLine:tColor4];
[self.colorBar1 setTextColor:self.blackExtract];
[self.colorBar2 setTextColor:self.blueExtract];
[self.colorBar3 setTextColor:self.redExtract];
[self.colorBar4 setTextColor:self.lineExtract];
NSLog(#"I have extracted colors");
}
I have 5 similar DrawViewControllers and all works with Drawing UIView.
1.Store UIColor as nsdata into nsuserdefaults
NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color];
2.Retrive UIColor from viewdidload
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
Try this it will work without error
1.Store UIColor as NSString into NSUserDefaults
-(void)storeColor
{
NSString *colString = [NSString stringWithFormat:#"%#", [UIColor whiteColor]];
[[NSUserDefaults standardUserDefaults] setObject:colString forKey:#"keyFontColor"];
}
2.Convert string into UIColor while retrieve
-(void)retriveColor
NSArray *values = [[[NSUserDefaults standardUserDefaults] objectForKey:#"keyFontColor"] componentsSeparatedByString:#" "];
NSLog(#"%d",[values count]);
UIColor *def_color = [[UIColor alloc] init];
if ([values count]==5) {
CGFloat red = [[values objectAtIndex:1] floatValue];
CGFloat green = [[values objectAtIndex:2] floatValue];
CGFloat blue = [[values objectAtIndex:3] floatValue];
CGFloat alpha = [[values objectAtIndex:4] floatValue];
def_color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
self.dateLabel.textColor = def_color;
}
else if ([values count]==3)
{
CGFloat white = [[values objectAtIndex:1] floatValue];
CGFloat alpha = [[values objectAtIndex:2] floatValue];
def_color = [UIColor colorWithWhite:white alpha:alpha];
self.label.textColor = def_color;
}
else
{
// its store default value while app loads first time
self.label.textColor.textColor = [UIColor blackColor];
}
}