how can i save the highlighted state of a Image view to user defaults,
and can i save the background Color of a Button to User defaults?(i change the color by click)
to save:
- (IBAction)char1_atheon_cp1_28:(id)sender {
if(_char1_atheon_cp1_28_image.highlighted == NO)
{
_char1_atheon_cp1_28_image.highlighted = YES;
_char1_atheon_cp1_28.backgroundColor =[UIColor greenColor];
[[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation([UIImage imageNamed:#"check.png"])forKey:#"char1_atheon_28_cp1"];
}
else
{
_char1_atheon_cp1_28_image.highlighted = NO;
_char1_atheon_cp1_28.backgroundColor =[UIColor clearColor];
[[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation([UIImage imageNamed:#"cross.png"])forKey:#"char1_atheon_28_cp1"];
}
}
to load:
if([[NSUserDefaults standardUserDefaults] objectForKey:#"char1_atheon_28_cp1"] != nil) {
NSData* imageData = [[NSUserDefaults standardUserDefaults]objectForKey:#"char1_atheon_28_cp1"];
UIImage* image = [UIImage imageWithData:imageData];
[_char1_atheon_cp1_28_image setImage:image];
}
Thanks Jürgen
Related
I have a table that needs to save the title of the cell selected to an array. My NSMutableArray is called dataArray and I'm using this line
[categoryItemSelected addObject: dataArray];
to save the selected item(s). I would like more than one item to be added to the array - the user should be able to select as many or as few rows as they like. Each one would be added to the dataArray.
here's my table didSelectAtIndexPath: method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int index = indexPath.row; id obj = [listOfCategories objectAtIndex:index];
//This toggles the checkmark
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
UIImage *image = [UIImage imageNamed:#"icon-tick.png"];
UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
[downloadButton setImage:image forState:UIControlStateNormal];
[downloadButton setFrame:CGRectMake(0, 0, 19, 19)];
[downloadButton setBackgroundColor:[UIColor clearColor]];
[tableView cellForRowAtIndexPath:indexPath].accessoryView = downloadButton;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//This sets the array
} else
{
cell.accessoryType = UITableViewCellAccessoryNone;
UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
[downloadButton setTitle:#"" forState:UIControlStateNormal];
[downloadButton setFrame:CGRectMake(0, 0, 0, 0)];
[tableView cellForRowAtIndexPath:indexPath].accessoryView = downloadButton;
}
// Save text of the selected cell:
UITableViewCell *cellSelected = [tableView cellForRowAtIndexPath:indexPath];
if ([cellSelected.textLabel.text isEqualToString:#"Food & Drinks"]) {
NSString *valueToSave = cellSelected.textLabel.text;
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"preferenceName"];
}
NSString *valueToSave = cellSelected.textLabel.text;
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"preferenceName"];
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"preferenceName"];
NSLog(#"savedValue %#", savedValue);
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// Customize archiver here
[archiver encodeObject:obj forKey:#"keyForYourArrayOfNSIndexPathObjects"];
[archiver finishEncoding];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"keyForYourArrayOfNSIndexPathObjects"];
NSKeyedUnarchiver *unarchiver;
unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:
[[NSUserDefaults standardUserDefaults] objectForKey:#"keyForYourArrayOfNSIndexPathObjects"]];
// Customize unarchiver here
categoryItemSelected = [unarchiver decodeObjectForKey:#"keyForYourArrayOfNSIndexPathObjects"];
[unarchiver finishDecoding];
if (categoryItemSelected == nil) {
//If it isn't been created - then create new array
[categoryItemSelected addObject: dataArray];
NSLog(#"list of categories selected in dataArray %#", dataArray);
}
NSLog(#"list of categories selected in dataArray %#", dataArray);
}
You have the parameters backwards. To add this object to dataArray do:
[dataArray addObject: categoryItemSelected];
You need to check if categoryItemSelected is nil first, since inserting a nil object into an array will throw an exception.
How can we set the button title for a button,i know this answer its simple,we need to set the title of the button for title ,but my need is somewhat diffrent ,i had a username which dynamically changes according to login.i set this in a button click and display it in a label within that button .my code for this is
- (void)getFacebookProfileFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"Got Facebook Profile: %#", responseString);
NSString *likesString;
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *username;
NSString *firstName = [responseJSON objectForKey:#"first_name"];
NSString *lastName = [responseJSON objectForKey:#"last_name"];
if (firstName && lastName) {
username = [NSString stringWithFormat:#"%# %#", firstName, lastName];
} else {
username = #"mysterious user";
}
[_loginButton setTitle:username forState:UIControlStateNormal];
_lblfaceusername.text = username;
[self refresh];
}
i need to display the user name in another button click and have to assing the title of that button to user name the code for this is
- (void)refresh {
if (_loginState == LoginStateStartup || _loginState == LoginStateLoggedOut) {
_loginStatusLabel.text = #"Not connected to Facebook";
[_loginButton setTitle:#"Login" forState:UIControlStateNormal];
_loginButton.hidden = NO;
} else if (_loginState == LoginStateLoggingIn) {
_loginStatusLabel.text = #"Connecting to Facebook...";
_loginButton.hidden = YES;
} else if (_loginState == LoginStateLoggedIn) {
_loginStatusLabel.text = #"Connected to Facebook";
[_loginButton setTitle:#"" forState:UIControlStateNormal];
_loginButton.hidden = NO;
}
}
i need to set the username in the [_loginButton setTitle:#"" forState:UIControlStateNormal];i want [_loginButton setTitle:username forState:UIControlStateNormal];
Anyhow you have set the button title in the method
- (void)getFacebookProfileFinished:(ASIHTTPRequest *)request
after facebook request done. Then, why you need to set that again in refresh method? Just comment out the line in LoginStateLoggedIn condition in refresh method.
//[_loginButton setTitle:#"" forState:UIControlStateNormal];
Edit
- (void)refresh {
if (_loginState == LoginStateStartup || _loginState == LoginStateLoggedOut) {
_loginStatusLabel.text = #"Not connected to Facebook";
[_loginButton setTitle:#"Login" forState:UIControlStateNormal];
_loginButton.hidden = NO;
} else if (_loginState == LoginStateLoggingIn) {
_loginStatusLabel.text = #"Connecting to Facebook...";
_loginButton.hidden = YES;
} else if (_loginState == LoginStateLoggedIn) {
_loginStatusLabel.text = #"Connected to Facebook";
NSString *username = [_loginButton titleForState:UIControlStateNormal];
[_loginButton setTitle:username forState:UIControlStateNormal];
_loginButton.hidden = NO;
}
}
What you need is storing a reference to that message at a location that both pieces of code can access. The typical way to do so is to add a NSString * _username in your interface definition, and setting it to the username when you receive it. That way you can always access it from any location that depends on the current value of it.
Memory management included, that would yield:
[_username release]; // Release possible previous login
_username = [username retain]; // Ownership needed
In refresh:
[_loginButton setTitle:_username forState:UIControlStateNormal];
In dealloc:
[_username release]; // Release ownership when not needed anymore
This allows you to access your variable at any location desired.
I have a reader application which can post text to Facebook .I already done that,i have a login-button as same as the facebook-login button,the user can login there and i retrieve the username from the Facebook and display instead of loge-out button,that means when the user login and came back the login-button title changes to loge-out thats the default behavior of the Facebook connect button,but i changed a little and set the title as username of the correspondent user.My problem is after login to the Facebook the the title of the button changes to username,but after redirected to some other page of the application and comes back it doesn't show the username the button title shows login.I tried a lot to solve this i even uses the NSUserDefault but no luck my entire code for this is
- (IBAction)loginButtonTapped:(id)sender
{
NSString *appId = #"HIDDEN1234";
NSString *permissions = #"publish_stream";
if (_loginDialog == nil) {
self.loginDialog = [[[FBFunLoginDialog alloc] initWithAppId:appId requestedPermissions:permissions delegate:self] autorelease];
self.loginDialogView = _loginDialog.view;
}
if (_loginState == LoginStateStartup || _loginState == LoginStateLoggedOut) {
_loginState = LoginStateLoggingIn;
[_loginDialog login];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"FB_logged"];
} else if (_loginState == LoginStateLoggedIn) {
_loginState = LoginStateLoggedOut;
_btnFacebookmain.enabled =NO;
[_loginDialog logout];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"FB_logged"];
}
[self refresh];
}
-(IBAction)_clickbtnFaacbukMain:(id)sender
{
StatusViewController *detailViewController = [[StatusViewController alloc] initWithNibName:#"StatusViewController" bundle:nil];
detailViewController.yourStringProperty = localStringValue;
detailViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:detailViewController animated:YES];
[UIView commitAnimations];
[detailViewController release];
UIView *popView = (UIView *)[self.view viewWithTag:106];
//ViewWithTag Number should be same as used while allocating
[popView removeFromSuperview];
}
- (void)refresh {
if (_loginState == LoginStateStartup || _loginState == LoginStateLoggedOut) {
_loginStatusLabel.text = #"Not connected to Facebook";
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"FB_logged"];
[_loginButton setTitle:#"" forState:UIControlStateNormal];
UIImage *buttonImage = [UIImage imageNamed:#"settings_connect1-facebook-icon"];
[_loginButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
//[[NSUserDefaults standardUserDefaults]removeObjectForKey:#"FB_LOGIN_STATUS"];
_loginButton.hidden = NO;
} else if (_loginState == LoginStateLoggingIn) {
_loginStatusLabel.text = #"Connecting to Facebook...";
_loginButton.hidden = YES;
UIImage *buttonImage = [UIImage imageNamed:#"settings_connect1-facebook-icon"];
[_loginButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
} else if (_loginState == LoginStateLoggedIn) {
_loginStatusLabel.text = #"Connected to Facebook";
NSString *username = [_loginButton titleForState:UIControlStateNormal];
[_loginButton setTitle:username forState:UIControlStateNormal];
[_loginButton setBackgroundImage:nil forState:UIControlStateNormal];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"FB_logged"];
_loginButton.hidden = NO;
}
}
- (void)getFacebookProfile {
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#", [_accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDidFinishSelector:#selector(getFacebookProfileFinished:)];
[request setDelegate:self];
[request startAsynchronous];
}
#pragma mark FB Responses
- (void)getFacebookProfileFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"Got Facebook Profile: %#", responseString);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *username;
NSString *firstName = [responseJSON objectForKey:#"first_name"];
NSString *lastName = [responseJSON objectForKey:#"last_name"];
if (firstName && lastName) {
username = [NSString stringWithFormat:#"%# %#", firstName, lastName];
} else {
username = #"mysterious user";
}
//[[NSUserDefaults standardUserDefaults] setObject:#"username" forKey:#"FB_LOGIN_STATUS"];
[_loginButton setTitle:username forState:UIControlStateNormal];
[self refresh];
}
#pragma mark FBFunLoginDialogDelegate
- (void)accessTokenFound:(NSString *)accessToken {
NSLog(#"Access token found: %#", accessToken);
self.accessToken = accessToken;
_loginState = LoginStateLoggedIn;
[self dismissModalViewControllerAnimated:YES];
[self getFacebookProfile];
[self refresh];
}
- (void)displayRequired {
[self presentModalViewController:_loginDialog animated:YES];
}
- (void)closeTapped {
[self dismissModalViewControllerAnimated:YES];
_loginState = LoginStateLoggedOut;
[_loginDialog logout];
[self refresh];
}
and in viewwillapper method
BOOL loggedd = [[NSUserDefaults standardUserDefaults] boolForKey:#"FB_logged"];
if (loggedd == YES) {
_btnFacebookmain.enabled = YES;
NSString *username = [_loginButton titleForState:UIControlStateNormal];
[_loginButton setTitle:username forState:UIControlStateNormal];
//[self refresh];
}
else
{
[_loginButton setTitle:#"" forState:UIControlStateNormal];
_btnFacebookmain.enabled =NO;
/* UIImage *buttonImage = [UIImage imageNamed:#"settings_connect1-facebook-icon"];
[_loginButton setBackgroundImage:buttonImage forState:UIControlStateNormal];*/
}
please look into this code and help me to solve this.
Thanks in advance.
and this is my first question here !
I use UIButton with UISwitch functionality and i want to save/retrieve state of UIButton.
Pls HELP!
Resolved!
Thanks Kalle and aBitObvious !
code i use :
.h
#interface RetinaViewController : UIViewController {
IBOutlet UIButton *mybutton;
}
-(IBAction) toggleUIButtonImage:(id)sender;
#end
.m
#implementation RetinaViewController
-(IBAction) toggleUIButtonImage:(id)sender{
NSString *value = #"ON";
NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
UIImage *unselectedImage = [UIImage imageNamed: #"OFFa.png"];
UIImage *selectedImage = [UIImage imageNamed:#"ONa.png"];
if ([sender isSelected]) {
[sender setImage:unselectedImage forState:UIControlStateNormal];
[sender setSelected:NO];
value = #"OFF";
[userPreferences setObject:value forKey:#"stateOfButton"];
}else {
[sender setImage:selectedImage forState:UIControlStateSelected];
[sender setSelected:YES];
value = #"ON";
[userPreferences setObject:value forKey:#"stateOfButton"];
}
[userPreferences synchronize];
}
- (void)viewDidLoad {
NSString *value = [[NSUserDefaults standardUserDefaults] stringForKey:#"stateOfButton"];
// If value is nil - disable the switch
if (value == nil) {
mybutton.selected = NO;
}
// If value is equal to ON
else if ([value compare:#"ON"] == NSOrderedSame) {
//NSLog(#"the switch is on");
// Set the switch to ON
mybutton.selected = YES;
} else {
//NSLog(#"the switch is off");
// Set the switch to OFF
mybutton.selected = NO;
}
[super viewDidLoad];
}
In the viewDidLoad of the view controller, put something like this:
NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
NSString *stateOfButton = [userPreferences stringForKey:#"stateOfButton"];
if ([stateOfButton isEqualToString:#"ON"])
{
//set button state to "selected"
}
else
{
//set button state to "not selected"
}
In my app, one if my goals is to use UISegmentedControl to choose the bg color of another screen. The problem is that I have tried to have it so that whenever you went to the options screen, the Segmented Control will remember the option you picked when you left the screen. It only remembers ONE OUT OF THE 5 OPTIONS!!! Here is the code in the options screen -
- (IBAction)changecolor:(id)sender {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if(segcolor.selectedSegmentIndex == 0){
//Red
UIColor *red = [UIColor redColor];
NSData *colordata = [NSKeyedArchiver archivedDataWithRootObject:red];
[prefs setObject:colordata forKey:#"ColorKey"];
}else if(segcolor.selectedSegmentIndex == 1){
//Yellow
UIColor *yellow = [UIColor yellowColor];
NSData *colordata = [NSKeyedArchiver archivedDataWithRootObject:yellow];
[prefs setObject:colordata forKey:#"ColorKey"];
}else if(segcolor.selectedSegmentIndex == 2){
//Green
UIColor *green = [UIColor greenColor];
NSData *colordata = [NSKeyedArchiver archivedDataWithRootObject:green];
[prefs setObject:colordata forKey:#"ColorKey"];
}else if(segcolor.selectedSegmentIndex == 3){
//Blue
UIColor *blue = [UIColor blueColor];
NSData *colordata = [NSKeyedArchiver archivedDataWithRootObject:blue];
[prefs setObject:colordata forKey:#"ColorKey"];
}else if(segcolor.selectedSegmentIndex == 4){
//Black
UIColor *black = [UIColor blackColor];
NSData *colordata = [NSKeyedArchiver archivedDataWithRootObject:black];
[prefs setObject:colordata forKey:#"ColorKey"];
}
}
The previous method is connected to the 'value changed' method in IB to the segmentedcontrol, segcolor. And also...
- (void)viewWillAppear:(BOOL)animated {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *colordata = [prefs objectForKey:#"ColorKey"];
if ([NSKeyedUnarchiver unarchiveObjectWithData:colordata] == [UIColor redColor])
segcolor.selectedSegmentIndex = 0;
if ([NSKeyedUnarchiver unarchiveObjectWithData:colordata] == [UIColor yellowColor])
segcolor.selectedSegmentIndex = 1;
if ([NSKeyedUnarchiver unarchiveObjectWithData:colordata] == [UIColor greenColor])
segcolor.selectedSegmentIndex = 2;
if ([NSKeyedUnarchiver unarchiveObjectWithData:colordata] == [UIColor blueColor])
segcolor.selectedSegmentIndex = 3;
if ([NSKeyedUnarchiver unarchiveObjectWithData:colordata] == [UIColor blackColor])
segcolor.selectedSegmentIndex = 4;
}
Just for reference, Black is the only option that remembers.
Now for in the main page...
- (void)viewWillAppear:(BOOL)animated {
//---------------------------------------------------------//
//----------------------BGData-----------------------------//
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *colorData = [prefs objectForKey:#"ColorKey"];
UIColor *bgcolor = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
self.view.backgroundColor = bgcolor;
if (bgcolor == [UIColor blackColor]) {
currentArtist.textColor = [UIColor whiteColor];
instructlabel.textColor = [UIColor whiteColor];
currentSong.textColor = [UIColor whiteColor];
} else if (bgcolor != [UIColor blackColor]) {
currentArtist.textColor = [UIColor blackColor];
instructlabel.textColor = [UIColor blackColor];
currentSong.textColor = [UIColor blackColor];
}
}
Who sees what's wrong?
Ouch. You cannot compare contents Objective-C objects with ==. Never. Use -isEqual: to compare UIColors.
And, why don't you directly store the segment index into the user defaults (-setInteger:forKey:, -integerForKey:)? Then you don't need to encode and decode the UIColors which is slow and memory consuming.