can't map single object (UIView, UIGesture) with two other objects (UIView)? - iphone

I have some confusion. Not really a bug or issue I am facing. I want to know something and I am not sure this is right place for this kind of question but here is my question:
In reference to my Question Here I was trying to map single gesture on two views.
Now I am keen to know that why this is not working? I went on basics that in case I have any NSObject subclass lets say if NSString and I add this in an NSMutableArray as follows:
NSString *strTest = #"Test String";
[aryTest1 addObject:strTest];
[aryTest2 addObject:strTest];
String gets added in both of array. Now what I am doing is I created a label, set tag for the label and added that in two views as follows:
UILabel *lblTemp = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
[lblTemp setTag:1];
[lblTemp setText:#"Label"];
[vw1 addSubview:lblTemp];
[vw2 addSubview:lblTemp];
Now every view has an array of subview. When we try to add an object in that view's subview why this is not being added in both of view?
I am getting a result that my second view is showing the label but first view is not having the label.
If I comment the last line of my code and don't add label in vw2 the label will be added in vw1. Than I tried a different thing.
UILabel *lblTemp = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
[lblTemp setTag:1];
NSMutableArray ary1 = [[NSMutableArray alloc] init];
NSMutableArray ary2 = [[NSMutableArray alloc] init];
[ary1 addObject:lblTemp];
[ary2 addObject:lblTemp];
both array has count 1. Thats mean that I have label added in my array. after that I tried to add array's object in view than even ame problem. Label is only being added in second view:
[vw1 addSubview:[ary1 objectAtIndex:0]];
[vw2 addSubview:[ary2 objectAtIndex:0]];
When I printed retainCount of Label after initialize, adding in array1 and array2 everytime the retaincount was 1. So I think the array are not keeping the reference of same object. Its a new object copied in array. Than why label is not being added in same view?
What is actual internal process for a object to add on any view's subview. As of I know subview is an Array type than what happening? Can anyone explain me?
Thanks in Advance

The difference is that addSubview automatically removes a view from it's super view before adding it to the new view (See the class reference: http://developer.apple.com/library/ios/ipad/#documentation/uikit/reference/uiview_class/uiview/uiview.html) while an array will happily accept an object even if it is in another array.
You can create a copy of the label and place it in the other view though if this is what you need to do.

Related

how to add multiple labels to a view programmatically without worrying about its Y position?

I have a situation here, I want to add user name with a check button in a view, looks simple :)...
Question is I may have single or multiple user, so I need to add it through code only, I want to add all names like a ladder with its corresponding check button.
What is the best way to do that?
I have tried by adding labels for each user.. While adding I wanted to set its top position one by one to make it aligned properly.. Do I have to calculate top like this? Any easiest way is there.. Like how they are doing in Android (relative Layout).
thanks
You can create array of usernames and use following code.
This is test code for your reference.
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:#"1"];
[arr addObject:#"2"];
[arr addObject:#"3"];
[arr addObject:#"4"];
[arr addObject:#"15"];
Now looping:
for (int i = 0; i<[arr count]; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 10*10*i, 100, 40)];
label.text = [arr objectAtIndex:i]; //usernames from array
[self.view addSubview:label];
}
The Objective-C equivalent of relativelayout is Cocoa Auto Layout
I would use a UItableView with a custom cell. The cell contains your input fields. This way you can have as many inputs as you like and they will always be layed out in order in the same way, and you don't need to write any funky code. You also get scrolling and memory management for free.

Display JSON as List in ViewController (Not in TableView)

I am producing a JSON string that I need to parse out and display onto the page. My JSON string outputs information about the contents of a CD like this:
[{"song_name":"Song 1","artist":"John","price":"$1"},
{"song_name":"Song 2","artist":"Anna","price":"$2"},
{"song_name":"Song 3","artist":"Ryan","price":"$3"}]
I would like to display the contents in my viewController in a list format displaying the song_name, artist, and price. I do not want to use a tableView to display this information, but would rather just have a list displayed. How might I go about doing this? I would assume that I need to use NSJSONSerialization, but have only used that for a tableView in the past. Thank you!
In addition to other answers, you can use only one label, just create NSMutableString (for dynamicly adding tracks info) with #"\n" between tracks info, pass it to label.text and set UILabel's property numberOfLines to 0
Follow these steps:
Parse the JSON and store the key-value pair(NSDictionary of CDs) in an NSArray (say infoArray)
Add a UIScrollview as a subview on your viewController's view.
Allocate UILabels dynamically, depending on infoArray count. Looking at your data I believe you can initialize labels with static frames i.e your y can remain static.
Add the text from the infoArray on this label.
Still, I would suggest use UITableView only. It is much simpler and a better approach
You make an array of dictionaries using NSJSONSerialization indeed, then you parse this array one by one and create a view of every dictionary. You're probably best of using a method for this:
-(UIView *) listView: (NSString *)songName andArtist:(NSString *)artist andPrice:(NSString *)price andIndex:(int)viewIndex {
//create your view here and do anything you want
UIView *subView = [[UIView alloc] init] autoRelease];
subView.frame = CGRectMake(0, viewIndex * 70, self.view.frame.width, 70);
//add labels and other stuff
// return the view
return subView;
}
The you add it to the current view by setting different Y values so they appear underneath each other by using the viewIndex of the former method... So if you have an array it goes something like this:
for (int i = 0; i < [array count]; i++) {
NSDictionary *dict = [array objectAtIndex:i];
NSString *songName = [dict valueForKey:#"song_name"];
NSString *artist = [dict valueForKey:#"artist"];
NSString *price = [dict valueForKey:#"price"];
UIView *tempView = [self listView:songName andArtist:artist andPrice:price andIndex:i];
[self.view addSubView:tempView];
}
You have to add it all to a scrollview otherwise you will run into the problem of to many rows on the page. Google for UIScrollView if you don't know how.
But I would recommend against this approach.. Tableviews are there with a reason. They are made for this stuff. Because the also provide for scrolling, drawing and refreshing. If you can, use them!

XCode - Dynamically created labels, when i change the text it changes it for the last one only

So i have a bunch of dynamically loaded labels..
Each of them has the same name because there is no telling how many there will be..
I have another method (not the one that created the labels) changing the text for one of the labels, but when i run it only the last label that was created will change..
I need it to change the one that has a certain tag or something..
Help is much appreciated, this website is yet to let me down.
self.myLabel cannot be connected to multiple labels, so it will contain the reference of last created label, you will have to create new label every time, and you can't track them by class properties, you have to access label by their tag.
you can set tag for each label, below is sample code,
for(int i=0; i< numberOfLabels; i++)
{
UILabel *label = [[UILabel alloc] init];
label.tag = i; // do not use tag 0 here.. u can use i+1, or i+100.. something like this.
[self.view addSubview:label];
}
to access labels,
UILabel *label = (UILabel*)[self.view viewWithTag: labelTag];
Okay since you dont have any code to show i guess i have to speculate.
What i understood is that you are creating Dynamic UILabels in ur code and you want to access them. Since you have same name for all the UILabels you might me loosing the previous UILabel when every time you create a new UILabel. So in order to keep track of how many UILabel you created you must add them in an Array. Declare an NSMutableArray in your viewController.h file and make sure in the viewDidLoad u allocate it like
arrForLabels = [[NSMutableArray alloc]init];
Since it is an NSMutableArray you can add object to it.
So when u create a UILabel make sure you add the same UILabel in the Array as well
for Instance
[arrForLabels addObject:yourLabel];
you can try to NSLog your Array to see its content.
Now all youu got to do is to Create a weak link like that
UILabel *tempLabel = [arrForLabels objectAtIndex:1];
now tempLabel will be the UILabel to change text
tempLabel.text = #"My New Text";
It will work fine.
Feel free to ask for any issues in it.

SSCollectionView SSCollectionViewItem - no Items displayed

I ran into difficulties with SSCollectionView and SSCollectionViewItem.
First of all I'd like to get it initialized from IB. But that won't work for me.
I have a SelectFooViewController which is:
#interface SelectFooViewController : SSCollectionViewController { ... }
and am using it as filesOwner of the corresponding XIB.
SelectFooViewController* selectFooVC = [[SelectFooViewController alloc]
initWithNibName:#"SelectFooViewController" bundle:nil];
But since it wont work I had to initialize its properties inside viewDidLoad() myself.
Furthermore I am not able to display anything except the backgroundColor of my SSCollectionViewItems. What I want is a textLabel and an image .
- (SSCollectionViewItem *)collectionView:(SSCollectionView *)aCollectionView itemForIndexPath:(NSIndexPath *)indexPath {
SSCollectionViewItem *item = [[[SSCollectionViewItem alloc] initWithStyle:SSCollectionViewItemStyleImage reuseIdentifier:itemIdentifier] autorelease];
SSLabel* label = [[SSLabel alloc] init];
[label setText:#"foo"];
item.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"foo.png"]];
item.textLabel = label;
[label autorelease];
return item;
}
I can confirm that the delegate methods (for determining the number Of rows, sections and such) are implemented and working as expected. But my items are all empty - but react onclick with the expected popup.
Does anyone see an error in what I did? - Thanks...
EDIT: I was also not able to display a local image by changing SSCatalog project
I just figured out, that I have to set the frame of each property (textLabel, detailTextLabel and imageView) myself. That fixed it.
When you create instance SelectFooViewController just insert this line
selectFooVC.view;
or
selectFooVC.view.hidden = NO;
And then add it to the view.
This is because the view is not initalised until you explicitly access it. Hence your items are loaded only when you click it and not immediately. You can call it a hack but i don't call it one. :-)

IB objects vs manually allocated objects in init/viewDidLoad

When I programmatically allocated a UILabel in my custom initWithNibName method, and later in viewDidLoad, tried to assign a string to it, the label was not pointing to anything. I didn't release it; the label shows on the screen. If I create the label in IB, and assign text to it in viewDidLoad, it works.
Is it against a rule to set up manually allocated objects in viewDidLoad?
Why is it not pointing to anything, even though viewDidLoad is called after my init?
From the doc of viewDidLoad:
This method is called after the view controller has loaded its associated views into memory. This method is called regardless of whether the views were stored in a nib file or created programmatically in the loadView method. This method is most commonly used to perform additional initialization steps on views that are loaded from nib files.
In my init:
_descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 218, 280, 10)];
_descriptionLabel.numberOfLines = 0;
_descriptionLabel.lineBreakMode = UILineBreakModeWordWrap;
_descriptionLabel.font = [UIFont systemFontOfSize:12.0];
_descriptionLabel.adjustsFontSizeToFitWidth = NO;
_descriptionLabel.text = #"Description not found.";
_descriptionLabel.backgroundColor = [UIColor clearColor];
In viewDidLoad, the variable's value is 0x0.
It's the same with my manually allocated UIButton, which is fully working once the view loads.
If you want to create the UILabel programatically you can, but you still do it in viewDidLoad (as opposed to initWithNibName).
Don't be afraid to do UI setup in viewDidLoad. It is provided to add any static UI elements BEFORE the view appears on screen.
The view will not appear until just before viewDidAppear:(BOOL)animated is called.
If you have dynamic content configure it in viewWillAppear:(BOOL)animated. (This looks like your situation)
Then make sure you add it to the view:
[self.view addSubview:myLabel];
If you need future access to your new label, you will need to create an ivar to hold a pointer to it.
In the code posted, the _descriptionLabel UILabel is not retained and will be released before the view is drawn.
Try
_descriptionLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20, 218, 280, 10)] retain];
Make sure you put [_descriptionLabel release] in dealloc. This assumes _descriptionLabel is an instance variable.
This basically applies to any object you create with alloc, copy, or new.