Adding different icons to each cells in table view - iphone

I want to add different icons to the table view present in my app.Can anyone guide me through a proper array or if possible show some sample code or example.Any help will be appreciated.
Thanks,
Christy

Say the icons are stored as icon0.png, icon1.png and so on in the app bundle.
You can give the icon for each cell as
cell.imageView.image = [UIImage imageNamed:
[NSString stringWithFormat:#"icon%d.png",indexPath.row]];
Swift
cell.imageView?.image = UIImage(named: "icon\(indexPath.row).png")

Well, you have an array somewhere to return the correct number in numberOfRowsInSection. That array is the one you use to fill up the cells. If you only want to display icons in your cells, your array of icons is like that.
So, for example:
UIImage *one = ...;
UIImage *two = ...;
[arrayIcons addObject: one];
[arrayIcons addObject: two];
and in numberOfRowsInSection, return [arrayIcons count].
In the method cellForRowAtIndexPath, you have the variable indexPath. If you want to know which cell you have, you use: indexPath.row.
So, if you load the cell (probably custom, see other answers), which has a UIImageView (say it's named: imageView), and you load the icons in the cells like this:
cell.imageView = [UIImage imageWithContentsOfFile:[arrayIcons objectAtIndex:indexPath.row]];

You wil have to define custom cells for your UITableView.
This tutorial is what you are looking for.

Related

UITableView design

I have UITableView where I want design as below.
For this I have images as below.
bottomRow.png
middleRow.png
topAndBottomRow.png
topRow.png
For this I have used below code inside -(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UIImage *selectedImage;
if (indexPath.row==0) {
selectedImage = [UIImage imageNamed:#"topRow.png"];
} else if (indexPath.row == ([products count]-1)) {
selectedImage = [UIImage imageNamed:#"bottomRow.png"];
} else {
selectedImage = [UIImage imageNamed:#"middleRow.png"];
}
if ([products count]==1) {
selectedImage = [UIImage imageNamed:#"topAndBottomRow.png"];
}
UIImageView *selectedBackgroundImageView = [[UIImageView alloc] initWithImage:selectedImage];
cell.selectedBackgroundView = selectedBackgroundImageView;
selectedBackgroundImageView = [[UIImageView alloc] initWithImage:selectedImage];
cell.backgroundView = selectedBackgroundImageView;
Now, everything works perfect.
BUT my designer is insisting on below point.
On tableview, I can have 4 cells at one time. Now let's say I have 6 rows.
Now when I have 6 rows (and tableview can show only 4), the 4th row shows bottomRow.png which is obvious. But my designer is insisting, even the tableview is scrolled, you should have same design for all 4 rows.
Edit 1
First of all, sorry for not being clear.
Well when the UITableView loads, I can only see first 4 cells even there are 6 cells because I have set the height of tableview accordingly. To see rest 2 cells, I have to scroll down. I believe this is how table view works.
Now let's say there are only 4 records. For 4 records, table view looks like image I have.
Now when I have tableview size as 6 (with id as 1-6), the fourth row gets image middleRow.png. Here what my designer wanted is to see bottomRow.png.
Now let's say I scroll down. Now I see row with cell id as 3-6. Now cell with id 3 have middleRow.png, but my designer wanted to see topRow.png.
I know this is ugly, but this is what my designer wanted to see.
Any suggestions to get this done?
One way to achieve your goal: Use numberOfRows to find out if this cell is the last cell.
In your cellForRowAtIndexPath:
if (indexPath.row==0) {
selectedImage = [UIImage imageNamed:#"topRow.png"];
.....
else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1){
selectedImage = [UIImage imageNamed:#"bottomRow.png"];
}
EDIT:
Sorry, I misunderstood your question, I have another proposal that I think you may try...
customCell, with a custom method to set its image. For example,
[customCell setSelectedImage: [UIImage imageNamed:#"middleRow.png"];
2.
In cellForRowAtIndexPath, you can set all cells to be: middleRow.png
3.
After loading of tableView, run a checking method using [self.tableView visibleCells];
eg
- (void) setImageForTopAndBottomCells{
CustomCell *topCell = [[self.tableView visibleCells] objectAtIndex: 0];
CustomCell *bottomCell = [[self.tableView visibleCells] objectAtIndex: self.tableView.visibleCells.count-1];
[topCell setSelectedImage: [UIImage imageNamed:#"topRow.png"];
[bottomCell setSelectedImage: [UIImage imageNamed:#"bottomRow.png"];
}
If your tableView is scrollable, set your ViewController as a UIScrollView delegate, in your delegate method scrollViewDidScroll, run the setImageForTopAndBottomCells method again.
There could be better ways for achieving what you want than the one I proposed, let me know if you found one.
What about using a combination of scrollViewDidScroll:, indexPathsForVisibleRows and reloadRowsAtIndexPaths:withRowAnimation: with something like this:
Every time the table view scrolls you get the list of visible rows using the UIScrollViewDelegate method scrollViewDidScroll:
If it scrolled enough to change the background, call the UITableView's reloadRowsAtIndexPaths:withRowAnimation: passing all the index paths that needs new background
Instead of using indexPath.row == 0 to find the top you would use [indexPath isEqual:[tableView indexPathsForVisibleRows][0]] and the same thing for the other rows
Hope this helps.
You can use middlerow.png as background view of your UITableViewCell in CellForRowAtIndexPath method. Below is the code
cell.backgroundView = [[UIImageView alloc] initWithImage[[UIImageimageNamed:#"middlerow.png"]stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];
And after this you can change the Corner radius (add border color/width) of your table view. But for this first you will have to add QuartzCore framework.
self.table.layer.borderColor=[[UIColor colorWithRed:209.0/255 green:209.0/255 blue:209.0/255 alpha:1.0] CGColor];
self.table.layer.borderWidth =3.0;
self.table.layer.cornerRadius =10.0;
Hope this helps.
You can Use this:
NSArray *visible = [tableView indexPathsForVisibleRows];
NSIndexPath *indexpath = (NSIndexPath*)[visible objectAtIndex:0];
-(NSArray *)indexPathsForVisibleRows returns an array of index paths each identifying a visible row in the receiver.So once you get the visible rows, you can use the required image according to indexpath.row.

how to show images at cell.imageview.image from NSArray?

Image Array=[NSArray arrayWithObjects:[UIImage imageNamed:#"1 (1).gif"],
[UIImage imageNamed:#"1 (2).gif"],[UIImage imageNamed:#"1 (3).gif"],[UIImage imageNamed:#"1 (4).gif"],[UIImage imageNamed:#"1 (5).gif"],[UIImage imageNamed:#"1 (6).gif"],[UIImage imageNamed:#"1 (7).gif"],nil];
//here is another array of objects showing in table view
alphabetsArray =[[NSMutableArray alloc]initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z",nil];
//everything working fine until when i add this code,app crashes with SIGABRT
cell.imageView.image=[UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]];
Actually i need to ask some more things:
Is there any problem if number of images in array isn't equal to number of object in tableview?
Is there any other way to add images if they are huge in number except of uiimage imageNamed:"whatever.jpeg"
What if add a folder and give its address or name and it picks up images by itself..
What is most reasonable method of adding images in project if they are 250 in number(i-e sqlite,coreData,hardcode in project as i did)?
First, there is issue with this line [UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]].
The [imageArray objectAtIndex:indexPath.row] is returning UIImage object in your current implementation, and you are trying to get UIImage with name of UIImage object.
You should just return the UIImage object directly to the cell.imageView.image.
cell.imageView.image = [imageArray objectAtIndex:indexPath.row];
Second, I am not sure how many rows are there in the table, but the method objectAtIndex can throw exception if the index is more than the number of elements in the array, causing app crash.
1) There would be no problem with this, unless you want to have the same number. It won't throw an error, but your app logic will not work properly.
2) Not that i know of, It's easy to do this though, use an easy naming convention such as image01, That way you can just copy and paste the code and change the ending numbers of the image
3) Im not sure of what you are asking.
4) Typically you would just need to add the images to your project via drag-N'-drop or by picking the files. Core data and sqlite are for the actual app that you are developing, not to store images in Xcode.
As for the main question, You say you want to show the images from an NSArray, if thats the case, just get the index path of the tableview, and look up the corresponding image using objectAtIndex:
Hope that helps a bit :)
Actually i have figured something out , there is an easy way to do.
cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#.gif", [TextShownInTableArray objectAtIndex:indexPath.row]]];
i have alphabetics in this array, and i wanted to use different images with each of the alphabet, so just added images in project with same name as alphabets had. it worked fine with this line of code. TextShownInTableArray is your array with text :)
Image Array=[NSArray alloc]initWithObjects:[UIImage imageNamed:#"8.gif"],
[UIImage imageNamed:#"2.gif"],[UIImage imageNamed:#"3.gif"],[UIImage imageNamed:#"6.gif"],[UIImage imageNamed:#"5.gif"],[UIImage imageNamed:#"4.gif"],[UIImage imageNamed:#"7.gif"],nil];
your array alloc and that array 'retain' this array and try this code .thanks
[imageArray retain];
only change in your code this line . and solve your problem
cell.imageView.image=[imageArray objectAtIndex:indexPath.row];
i hope this code useful for You . Check this
cell.imageView.frame = CGRectMake(5, 5, 50, 50);
NSString *imgstr = [[Arr objectAtIndex:indexPath.row] objectForKey:#"thumb"];
cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgstr]]];

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!

How to implement table with row and column

How to implement a table like in the image? Table with Row and column? Can any tell me the refrence for iphone
The columns are just an illusion.
This is done by subclassing UITableViewCell and designing the cell to have a UIImageView and three UILabels.
Assign the imageView and labels to properties of your subclass and you can configure it this way...
Object *object = [self.datasource objectAtIndexPath:indexPath];
cell.imageView.image = object.image;
cell.subCategoryLabel.text = object.subcategory;
cell.dateLabel.text = object.dateString;
cell.scoreLabel.text = [NSString stringWithFormat:#"%i", object.score];
or something like this.
Then the layout of the labels gives the illusion of having columns.
You need to create custom cell exact according to your requirement. Add data dynamically by adding row and column. Read this http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/tableview_iphone/TableViewCells/TableViewCells.html documentation before implementing custom cell.

How to set UITableViewCell highlighted image

I want to launch a method every time when user just highlights a cell (doesn't select it) in UITableView. Could you tell me please, how is it possible to do this ?
I want to do it because I have a custom cell with a pictures on it and I want to change pictures every time when user highlights the cell.
UPD: By highlight I mean that user just highlights a cell and don't release the finger from it. By select I mean when didSelectRowAtIndexPath is being launched (so the user releases the finger from the cell after he presses on it)
How do you envisage the user would 'highlight' a cell rather than 'selecting' one?
In iOS (or any touch based environment really) there is no concept of just highlighting a cell rather than selecting one. The only callback you get when the user touches a cell is didSelectRowAtIndexPath:
It might be worth reading up on the documentation on tables here.
UPDATE:
Ah OK, in that case you want to set the highlightedImage property of the cells imageView a bit like this;
cell.imageView.image = [UIImage imageNamed:#"normal_image.png"];
cell.imageView.highlightedImage = [UIImage imageNamed:#"highlighted_image.png"];
I didnt understand your question..you dont you want to use the method selectRowAtIndexPath?
if you want to execute a method when user select a row:
-you can use the method selectRowAtIndexPath and execute your method.
you can also create an invisible UIButton inside cell and when click in a cell you will click in button and execute your method . . .
From iOS 6.0, UITableViewDelegate has 3 methods to handle cell highlighting:
- tableView:shouldHighlightRowAtIndexPath:
- tableView:didHighlightRowAtIndexPath:
- tableView:didUnhighlightRowAtIndexPath:
You should use them, like in this example:
- (BOOL)tableView:(UITableView*)tableView shouldHighlightRowAtIndexPath:(NSIndexPath*)indexPath
{
return YES;
}
- (void)tableView:(UITableView*)tableView didHighlightRowAtIndexPath:(NSIndexPath*)indexPath
{
MyTableViewCell* cell = (MyTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
cell.myImageView.image = [UIImage imageNamed:#"myCellHigh"];
}
- (void)tableView:(UITableView*)tableView didUnhighlightRowAtIndexPath:(NSIndexPath*)indexPath
{
MyTableViewCell* cell = (MyTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
cell.myImageView.image = [UIImage imageNamed:#"myCellUnhigh"];
}