iOS 5 Location of Objects on Screen - ios5

I am creating a test app that will add multiple UIImageViews with images. The user will be able to move and rotate these images around. I have the UIGestureRecognizers in place and working, but I need to also keep track of the location of where the user leaves the images on screen. That way if they close the app and come back, where they placed the images will be remembered.
I know I should be using NSUserDefaults for this, but my question is how do I keep track of possibly a very large amount of UIImageView's locations on screen. I assume I need to somehow get the x/y coordinates of them and store that with NSUserDefaults.
Anyone have suggestions of how to do this?
-Brian

UIView's have a property subviews. I suggest looping through the array. Here is an example:
NSMutableDictionary *coordinates = [[NSMutableDictionary alloc] init];
for (id subview in view.subviews) {
if ([subview isKindOfClass:[UIImageView class]]) {
[coordinates setObject:[NSValue valueWithPoint:subview.frame.origin] forKey:imageViewIdentifier];
}
}
//store coordinates in NSUserDefaults
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:coordinates forKey:#"ImageViewCoordinates"];
[userDefaults synchronize];
Instead of storing the entire image view as the key in the coordinates dictionary, you can use some identifier for it to conserve memory. The object is an NSValue, so to get the x/y values from it you can use [[value pointValue] x] or [[value pointValue] y].
Here is an example of reading the data back (and restoring the view back to normal).
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *coordinates = [userDefaults dictionaryForKey:#"ImageViewCoordinates"];
//Key can be any type you want
for (NSString *key in coordinates.allKeys) {
UIImageView *imageView;
//Set UIImageView properties based on the identifier
imageView.frame.origin = [coordinates objectForKey:key];
[self.view addSubview:imageView];
//Add gesture recognizers, and whatever else you want
}

Related

Why is my nsuserdefaults text not showing up instantly? [duplicate]

This question already has an answer here:
NSUserDefaults Lose Newly Saved Data if App Killed Within 10 Seconds
(1 answer)
Closed 9 years ago.
I push a button that saves an nuserdefaults text then the button takes me to the next view controller (View Controller 2).Then the UILabel in second controller reads the text. However, I always have to push the button twice to get the UILabel in View Controller 2 to read the nsuserdefault text. This is weird because my navigation title bar in second view controller can read nsuserdefaults instantly without pushing the button more than twice.
Viewcontroller 1
NSString *calories = #"Test:1, 2, 3";
[[NSUserDefaults standardUserDefaults]
setObject:calories forKey:#"Text"];
View Controller 2
clabel=[[UILabel alloc] initWithFrame:CGRectMake(0,30, 320, 30)];
clabel.text=[[NSUserDefaults standardUserDefaults]stringForKey:#"Text"];
clabel.textColor=[UIColor blackColor];
clabel.font = [UIFont fontWithName:#"Helvetica-Bold" size: 12.0];
clabel.backgroundColor =[UIColor clearColor];
clabel.adjustsFontSizeToFitWidth=YES;
[self.view addSubview:clabel];
Try this one:
[[NSUserDefaults standardUserDefaults]
setValue:calories forKey:#"Text"];
Then
[[NSUserDefaults standardUserDefaults]ValueforKey:#"Text"];
You need to synchronize the user defaults to write them to storage, etc:
NSString *calories = #"Test:1, 2, 3";
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:calories forKey:#"Text"];
[userDefaults synchronize];
Edit: Not actually required
Ok, I figured out my problem why this was working for my navigation bar ,but not my uilabel.You have to add nsuserdefaults before the code that switches view controllers.
You are forgot below line of code. Once you put the data in userdefaults then you need to write synchronize.
[userDefaults synchronize];

Showing UIPickerview selected value

I have a UIPickerView which displays the array of items. When i select an item, it can be passed to all my view controller. Now my problem is after moving to different view controllers and returned back to the UIPIckerView it shows the first array item and not the item which i selected. How can i view the selected item?
//in viewDidLoad()
itemsArray = [[NSArray alloc] initWithObjects:#"5", #"10", #"20", #"30", #"50",#"100", nil];
// if i select 20 and moved to other pages of my controllers and
// return to the UIPickerView i can see the 5 as selected not the 20
Any suggestions?
Hi use NSUserDefaults for holding the current selected value using ,
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithInt:albumCount] forKey:#"AlbumCount"];
[defaults synchronize];
for retrieving sake ,
albumCount = [defaults integerForKey:#"AlbumCount"];
Can do it in different ways
Use pass by value or reference in different VCs
Store the selected value in some other place which is persistant throughout the runtime and use it
Like
NSUserdefaults,
Inside a singleton instance[bad idea,memory retained all time but
still an option]
SQLite DB [ok ok,still hard in this case alone]
coredata [ sofisticated in this purpose]
In a file [write and read from file operations]
You will need to store the selected value somewhere, either as a property on a view controller or model, or in a central location like NSUserDefaults.
Then, when you return to that view controller with the UIPickerView you can use
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated to set the value.
Depending on what you want to achieve, and how you're approaching opening a further view it may be as simple as declaring #property int currentIndex, setting currentIndex = indexForSelectedItem and then in your viewWillAppear using it to alert your view what the last selected was.

How to save the subView that has been added with NSUserDefaults?

I'm working in a book app, and I want to use a page marker to help the user remember where he stopped reading. So I have added a bar button with an image ("mark.png"). A mark view will be added to the chapter view when it is tapped, and if it is been tapped again the mark will be removed from the superView. I'm using this code:
- (void)showMark {
if (![markView superView]) {
[chapterOne addSubView:markView];
}
else {
[markView removeFromSuperView];
}
}
It is working fine but ever time I exit the app and rerun again the mark view is gone, so how can I keep it?
I found some forums talking about the NSUserDefaults to save actions but I really don't know how to use it with my code. Any help will be appreciated.
You can't use NSUserDefaults to save entire views, but you can save the parmeters that would help determine where the bookmark should be set.
For example if you are basing the book mark by a page number you could save the page to the NSUserDefaults when the user leaves the view controller.
Example:
[[NSUserDefaults standardUserDefaults] setInteger:23 forKey:#"bookMarkPage"];
[[NSUserDefaults standardUserDefaults] synchronize];
When the user comes back the the view controller you can check if there is a bookmark:
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"bookMarkPage"] != nil) {
int pageNumber = [[NSUserDefaults standardUserDefaults] objectForKey:#"bookMarkPage"];
[self setBookmarkForPage:pageNumber];
}
Possible bookmark construction method:
- (void) setBookmarkForPage:(Int)pageNumber {
// run through the logic of placing the bookmark on the correct page
}
You can use whatever parameters you need to determine where to place the book mark. When a user originally places the bookmark what parameters you use to figure out where to place the bookmark? Try to use the same logic for when a user first places the bookmark.
I don't know exactly what you want to save, but you can just about any kind of data with NSUserDefaults, like this:
[[NSUserDefaults standardUserDefaults] setInteger:123 forKey:#"CurrentPageNumber"];
When you have set all the values you need, save them:
[[NSUserDefaults standardUserDefaults] synchronize];
Then when app opens, check to see if the value is set. If it is draw your marker.
if ([defaults valueForKey:#"CurrentPageNumber"] != nil) {
int pageNumber = [defaults valueForKey:#"CurrentPageNumber"]
if (pageNumber == 1) {
[chapterOne addSubView:markView];
}
else {
[markView removeFromSuperView];
}
}
The other answers state great ways to work around the issue. Just to clarify, UIView or any of the derivatives are not supported for NSUserDefaults. NSUserDefaults allows just primitive object types (NSString, NSNumber, NSArray, and NSDictionary). There might be one or two I missed. But UIView or UIViewController object types can't be saved in NSUserDefaults.

Restore the state of UIScrollview

I'm trying to figure out how to save the state of a UIScrollView. For example, I have several images and Labels in a UIScrollView that are loaded from xib.
Now my question is how can I make it when the user returns to this page the state of scrollview is the same that they stopped scrolling at? Does anyone know how to accomplish this? Thanks.
I've found this:
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
[defaults setFloat: scrollview.contentOffset.x forKey: #"myScrollPositionX"];
[defaults setFloat: scrollview.contentOffset.y forKey: #"myScrollPositionY"];
and for restore:
scrollView.contentOffset = CGPointMake([defaults floatForKey: #"myScrollPositionX"], [defaults floatForKey: #"myScrollPositionY"]);
Where should I implement this? Sorry I'm a newcomer, so pls make it simple :D
You can save the position to the defaults in the viewWillDisappear:animated method of your view controller, and set the content offset in the viewWillAppear:animated method, so the state is saved as the user leaves the view, and is restored just before the user re-enters the view.

Keeping and Saving New Rating at Ratingview Startup

This is on a sidenote to my previous question about ratingview
I have this code:
[starView displayRating:1.5];
...however, I want it to be changed according to this:
-(void)ratingChanged:(float)newRating {
ratingLabel.text = [NSString stringWithFormat:#"Rating is: %1.1f", newRating];
//....
How can I make it displayRating: newString...
Can anyone show me how to do this please?
Update
Update
i have this code in place from what ive seen from your instructions (without the labels those are irrevelant)
-(void)viewDidLoad {
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSLog(#"Initializing rating view");
[starView setImagesDeselected:#"0.png" partlySelected:#"1.png" fullSelected:#"2.png" andDelegate:self];
[starView displayRating:[[defaults floatForKey:#"Rating"] stringValue]]; }
however i am getting an error message incompatible type for argument 1 of display rating and cannot convert to pointer type errors while building...
If you want to save a simple one value rating between application launches you should use NSUserDefaults like this:
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
// Save
[defaults setFloat:newRating forKey:#"Rating"];
// Read
float *savedRating=[defaults floatForKey:#"Rating"];
Update:
im sorry im a 16 year old and i have
no idea how to implement this into my
code. ive never used the nsuserdefault
class before i have this code how
would i do it.
-(void)viewDidLoad {
[super viewDidLoad]
theLabel.text = myLabel
theLabel2.text =myLabel2
NSLog(#"Initializing rating view")
[starView setImagesDeselected:#"0.png" partlySelected:#"1.png" fullSelected:#"2.png" andDelegate:self]
[starView displayRating:savedRating]
}
Well, to start, you would most likely want to put this code in viewDidAppear instead so that it is called every time the view appears. viewDidLoad is only called the first time the view controller loads from the nib file.
Suppose you wanted to set the text of theLabel to the value of the saved rating. It would look like this:
-(void)viewDidLoad {
[super viewDidLoad]
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
theLabel.text = [[defaults floatForKey:#"Rating"] stringValue];
theLabel2.text =myLabel2
NSLog(#"Initializing rating view")
[starView setImagesDeselected:#"0.png" partlySelected:#"1.png" fullSelected:#"2.png" andDelegate:self]
[starView displayRating:savedRating]
}