Dynamic initialization of controls in iphone - iphone

I am tying to add the values from an array to a number of text boxes in my view. it is possible for me to make it work by implementing
a1.text=[arrayName objectAtIndex:1];
Similarly i am having a1, a2, a3,... a45,... a60,... upto a99
Here "a1" is the outlet of a particular textfield. what i need is that, i have a plenty of controls on my screen. so its not possible for me to add each and every line. is there any way to add the values from the array to the corresponding textboxes.
what i need is to have a loop which will recursively add the values from the array to the textboxes. which implements the following manually written code
a1.text = [arrayName objectAtIndex:1];
a1.text = [arrayName objectAtIndex:2];
...........
a99.text = [arrayName objectAtIndex:99];
can any one help me please...
Thanks in advance,
Shibin

When you create you controls (e.g. textfields) set their tag property to a value that can later be used to determine an index for corresponding value in your array:
for (int index = startTag; index <= endTag; ++index){
UITextField* field = (UITextField*)[view viewWithTag:index]; // or [view viewWithTag:index + someValue];
field.text = [arrayName objectAtIndex:index];
}

Related

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!

Recognizing all objects generated by a loop

This question is a bit related to one I posed previously entitled "Recognizing UIButton from a loop".
In this case, I have generated a bunch of UITextFields with a loop. When the value of one of them is changed, I'm able to recognize which textfield it was.
However, I want to then edit every textfield that was generated. Specifically, I get input from the one textfield that was edited, and I want to recalculate the other textfields based on the input and name of the recognized textfield.
How do I call for every one of the other generated, non-edited textfields to be modified?
/Vlad
Since you are already using tags, this is what viewWithTag is used for:
// Get a reference to the textfield with tag 3
UITextField *textField3 = (UITextField *)[self.view viewWithTag:3];
// Calculate your new value
float result = 4.32; // Calculate the value that you want the textfield with tag 3 to display
// Change the contents
textField3.text = [NSString stringWithFormat:#"%f", result];
store the text fields in an array, then when you want to change the value
[self.myTextFieldArray enumerateObjectsUsingBlock:^(UITextField *textField, NSUInteger idx, BOOL *stop){
if (![textField isEqual:theTextFieldThatWasEdited])
textField.text = #"whatever text you want";
}];

Is it possible to create multiple columns in UITableView?

I want to add more columns in my iPhone/iPad application. Is it possible to add more columns in one UITableView? Can you please suggest any sample code/block/project that using multiple columns in one UITableView? Please help me. Thanks in advance.
No it is not possible, in fact UITableView is badly named a represents a List more than a Table.
If you want to have multiple column, one method is to create specific cells, with multiple label, and pack your data by row then column.
short answer is no, but you always can create custom cell what will look like multiple columns
You can use my library, UIGridView.
It is created with UITableView, in which UITableViewCell contains many cells inside.
Here is how it looks like:
No Yuvaraj.M we can't create. but you do something like multicolumn by adding component like label or image or button what u want or else using custom cell.
I've done a grid by using a table view where I have basically faked it by adding subviews to a cell. So if you for example create a cell, add three subviews to it, you can then get the items you need by doing something like this when it asks you for a cell for a specific row:
// get the items for the row (a row is one cell)
NSArray *rowItems = nil;
int startIndex = indexPath.row * NumOfItemViewsPerRow;
if (startIndex + NumOfItemViewsPerRow < [items count]) {
rowItems = [items subarrayWithRange:NSMakeRange(startIndex, NumOfItemViewsPerRow)];
} else {
rowItems = [items subarrayWithRange:NSMakeRange(startIndex, [items count] - startIndex)];
}
Then just after that you can loop the subviews of your row something like this:
[cell.itemViews enumerateObjectsUsingBlock:^(MyItemView *itemView, NSUInteger idx, BOOL *stop) {
NSDictionary *item = [rowItems objectAtIndex:idx];
itemView.titleLabel.text = [item valueForKey:#"title"];
};
It is a bit fiddly, but the upside is that you get row unloading for free from the table view, so you don't have to mess with your own custom grid views or anything like that.
Hope that helps.

How to generate UITextFields dynamically with different name and accessing it from another place?

I have an iPhone application in which there are dynamically generated textfields to capture a value of product quantity. The default quantity is 1. I have generated textfields like this
for(int i=0;i<[array count];i++)
{
UITextField *i=[[UITextField alloc]init];
i.frame=CGRectMake(90, Yposqtytextfield, 60, 30);
i.borderStyle=UITextBorderStyleRoundedRect;
[self.scrollview addSubview:i];
i.delegate=self;
i.text=#"1";
i.tag=i;
[appDelegate.qtyArray addObject:i.text];
}
But I want values of quantities in next page. For that I have taken this qtyarray. Now the user is allowed to change quantity. So how can I change the value of quantity in the array. as declaration of textfield is local to that loop. So at next page navigation how can i get the values of all these textfields?
UITextField *aField = (UITextField*)[appDelegate.qtyArray objectAtIndex:0]
it should be
NSString *aValue = [appDelegate.qtyArray objectAtIndex:0];
because he is adding value of textfield not the textfield object itself.
you can access your qtyArray anywhere in the application. Since application delegate is singleton class. You can access value like this
NSString *aValue = [appDelegate.qtyArray objectAtIndex:0];

Convert a string + a number to an onject

I am new to Obj C, but familiar with OOP. I am working on a game that uses collision detection to score points and change UIImageView properties like background color.
I have a finite number of UIImageViews that are subviews of a larger view. I can manually check for collision and set the background colors of the UIImageViews accordingly. The problem is that this creates a rather large if / else block that I can see growing out of control. In JavaScript I can use a for loop and eval() to evaluate a string + i (the loop var) and then simply call the new var.backgroundColor = someColor;
It seems that eval is not used in OBJ C, so I am looking for an equivalent that will allow me to create a loop that executes the same block of code on a given object that only differs from other objects by name only:
Example:
if (someStatement == true){
object_01.someProperty = newProperty;
} else if (someOtherStatement == true){
object_02.someProperty = newProperty;
} else if (someOtherOtherStatement == true){
object_03.someProperty = newProperty;
}
I want to write the above as a loop. I realize I can use an Array, but if so, how? Also, I want to loop through CGRects which are not storing properly in an Array.
Any help greatly appreciated!
Damon
Creating your array:
NSMutableArray *items = [NSMutableArray array];
Populating your array with CGRects:
[items addObject:[NSValue valueWithCGRect:frame]];
Pulling a CGRect from the array:
CGRect frame = [[items objectAtIndex:0] CGRectValue];
Replacing an index in the array:
[items replaceObjectAtIndex:0 withObject:[NSValue valueWithCGRect:frame]];
The best way is to put object_01, object_02, ... into an array and then use `-[NSArray objectAtIndex:] to access the objects.
You could also use Key-Value Coding:
NSString *keyPath = [NSString stringWithFormat:#"object_0%d.someProperty", objectIndex];
[self setValue:newProperty forKeyPath:keyPath];
But as rpetrich mentioned, it's not good programming style.