UITableView - didSelectRowAtIndexPath Question? [duplicate] - objective-c

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
UITableView and Selecting Items
I am building a iPad app, and have ten Items in a UITableView. When I select option "Apple" I would like it to display a apple in the UIImageView on right. When I select "Orange" I would like it to display a Orange in the UIImageView on the right, and so on.
What is the simplest piece of code to accomplish this?

Assuming you have stored your values that you are displaying in some sort of NSArray or other type of data source (I'm going to assume NSArray), then you could do something like this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *selection = [myArray objectAtIndex:indexPath.row];
if ([selection isEqualToString:#"Apple"])
{
[myImageView setImage:[UIImage imageNamed:#"Apple.png"]];
}
elseif ([selection isEqualToString:#"Orange"])
{
[myImageView setImage:[UIImage imageNamed:#"Orange.png"]];
}
}

Building off of Thuggish Nugget's answer, you could incorporate the selection name right into the image string:
NSString *selection = [myArray objectAtIndex:indexPath.row];
[myImageView setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#.png", selection]]];
And you could condense that down into one line.

I answered this alredy for you.
Here is the SO question
It would be a good idea to respond to that same question with a comment if u still need help with a UITableView.
Here is the answer from the other question.
Either set the cell.imageView.highlightedImage, or in the didSelectRowAtIndexPath method, change the cell.imageView.image from nil to some [UIImage imageNamed:#"myImage.png"]:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCustomCellID = #"com.me.foo.cell";
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
    cell.textLabel.highlightedTextColor = [UIColor blueColor];
    cell.imageView.image = nil;
    cell.imageView.highlightedImage = [UIImage imageNamed:#"myImage.png"];
    return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(iPadRootViewControllerTableCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Do this if you didnt set the highlightedImage in cellForRowAtIndexPath
    // [self tableView:tableView cellForRowAtIndexPath:indexPath].imageView.image = [UIImage imageNamed:#"myApple.png"];
}
Edit (adding comments from other questions answer):
To get a specific item from an array for a row, just use the indexPath.row as the objectForIndex for your array.

Related

Objective-C: Self-Sizing Table View Cells with dynamic image's height after download

I wanna resize imageview'height after download image,but some wrong happened as first cell image when first load tableview;
then if I scroll table to make the cell be in visible again,it go to be normal as second image;
I don't known the size of image,can't get from server,how to fix it?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ShopingTableCell* cell = [tableView dequeueReusableCellWithIdentifier:#"shopingCell" forIndexPath:indexPath];
StoreDynamicsModel *model = storeArray[indexPath.row];
cell.contentLabel.text = model.name;
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.goods_img_url] placeholderImage:[UIImage imageNamed:#"defaultShort"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
dispatch_async(dispatch_get_main_queue(), ^{
cell.imgViewHeightConstraint.constant = image.size.height * ScreenWidth / image.size.width;
});
}];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
tableView.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = 120.f;
return self.tableView.rowHeight;
}
You can set content mode of UIImageView to Aspect Fit.
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
For ref:
How to manage UIImageView content mode?

add background image for sections in UITableView

is it possible to change background image of each sections in uitableview?
I want to add background image for each sections in uitableview
does anyone know how can I do that?
Thanks in advance!
like this picture --> put different background images for wednesday , Thursday and friday separately
Edit I want to add image 1 for wednesday image 2 for Thursday image 3 for friday and .....
how can I specify that ?
Edit
this the code for creating sections header I want to have background also
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if(section == 0)
return #"Monday";
else if(section == 1){
return #"Tuesday";
}else if(section == 2){
return #"Wednesday";
} else if(section == 3){
return #"Thuesday";
} else if(section == 4){
return #"Friday";
} else if(section == 5){
return #"Saturday";
}else
return #"Sunday";
}
You could change the background in the cellForRowAtIndexPath delegate method based on the indexPath, like so:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TaskCellRow";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
int maxRow = 3;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed: [NSString stringWithFormat: #"background_image%i.png", MIN(indexPath.row, maxRow)]]];
}
else
{
UIImageView *background = (UIImageView *)cell.backgroundView;
background.image = [UIImage imageNamed: [NSString stringWithFormat: #"background_image%i.png", MIN(indexPath.row, maxRow)]];
}
return cell;
}
// To change header backgrounds
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
int maxRow = 3;
UIImageView *headerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed: [NSString stringWithFormat: #"background_image%i.png", MIN(section, maxRow)]]];
return headerView;
}
You would then just create images, numbered for the desired amount header/rows, ie. background_image0.png, background_image1.png, background_image2.png, ... and so forth. The MIN will cap the amount off at the whatever you decide is the max backgrounds. Hope that helps.
EDIT: Changed cellForRowAtIndexPath based on Henri's comments. I overlooked that, thanks! This is for ARC compatibility.
You can use:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
to specify any kind of UIView for a section header. This other delegate method:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
lets you specify the height.
Just alloc/init the UIView in the first one using the table's width and the height from the second method and then add any number of views to it, such as a UIImageView for a background then a label for the title.
Iterating (and mostly correcting) example given by ezekielDFM. Note, this code is not ARC compatible (which previous example may have been).
// To change cell backgrounds
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"TaskCellRow";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
int maxRow = 3;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIImageView *imageView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: [NSString stringWithFormat: #"background_image%i.png", MIN(indexPath.row, maxRow)]]] autorelease];
cell.backgroundView = imageView;
} else {
// Reusing, we need to swap out the image of the background
cell.backgroundView.image = [UIImage imageNamed: [NSString stringWithFormat: #"background_image%i.png", MIN(indexPath.row, maxRow)]];
}
return cell;
}
// To change header backgrounds
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
int maxRow = 3;
UIImageView *headerView = [[[UIImageView alloc] initWithImage:[NSString stringWithFormat:#"background_image%i.png", MIN(section, maxRow)]] autorelease];
return headerView;
}
As i guess it is not possible to change the background image for Table view Sections. If you want to do such a requirement, please try with cell for row as Sections. i.e. for each row treat as section of table & in that add 1 more table view with different tag. It will full your req. or else for each row take

cellForRowAtIndexPath not being called

I have a view that adds another view on top in this manner:
- (void)showAreaEditView {
NSLog(#"SHOWING AREA EDITOR VIEW");
if (self.thisAreaEditorView == nil) {
// Create View
AreaEditorView *tmpViewController = [[AreaEditorView alloc] initWithNibName:#"AreaEditorView" bundle:nil];
self.thisAreaEditorView = tmpViewController;
[tmpViewController release];
// Hide the back button
self.thisAreaEditorView.navigationItem.hidesBackButton = YES;
}
self.thisAreaEditorView.myInspectionID = self.myInspectionID;
self.thisAreaEditorView.loggedIn = loggedIn;
self.thisAreaEditorView.loggedInGroup = loggedInGroup;
// Slide view up
[self.view addSubview:thisAreaEditorView.view];
CGRect endFrame = CGRectMake(self.view.frame.size.width/2 - thisAreaEditorView.view.frame.size.width/2,
self.view.frame.size.height/2 - thisAreaEditorView.view.frame.size.height/2,
thisAreaEditorView.view.frame.size.width,
thisAreaEditorView.view.frame.size.height);
CGRect startFrame = endFrame; // offscreen source
// new view starts off bottom of screen
startFrame.origin.y += self.view.frame.size.height;
self.thisAreaEditorView.view.frame = startFrame;
// start the slide up animation
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.6];
thisAreaEditorView.view.frame = endFrame; // slide in
[UIView commitAnimations];
}
I'm sure you can just ignore the slide part, I feel the addSubview is relevant.
Then in thisAreaEditor I have the view with the table and buttons and such. UITableView delegate/datasource is going to File's Owner as normal.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"numberOfRowsInSection returning %d", [tableData count]);
[tableData count];
}
This function numberOfRowsInSection returns 4
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSString *thisText = [tableData objectAtIndex:indexPath.row];
cell.textLabel.text = thisText;
NSLog(#"looking at cell %d text:%#", indexPath.row, thisText);
return cell;
}
But cellForRowAtIndexPath never gets called.
I'm at a loss here, I have no idea how it can seem to work fine but one of the delegate functions simply not be called.
I have tried [bigTable reloadData] and so on, the table just never gets populated and no logs from the function output.
Thanks in advance.
You might have just edited this out, if so I'm sorry, but it looks like you forgot to return tableData's count.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(#"numberOfRowsInSection returning %d", [tableData count]);
    return [tableData count];
}
It seems you're missing UITableViewDelegate.
If you're using Interface Builder, right click the table view outlet and drag both delegate and datasource to File's Owner.
And if not using Interface Builder add this where you init your tableView
bigTable.delegate = self;
bigTable.dataSource = self;
Remember to import the UITableViewDelegate and UITableViewDataSource protocols, just as Srikar says.
Hope this is to any help.
Cheers!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath is also not called when the tableview's height is not set.
Maybe you did not set the tableView delegate as self or the datasource as self. Add this code & see if it works now -
[tableView setDelegate:self];
[tableView setDataSource:self];
Also in your header file inherit these delegates - UITableViewDelegate, UITableViewDataSource
#interface yourViewController: UIViewController <UITableViewDelegate, UITableViewDataSource>
Hope this helps.
This is a older link, but I wanted to update this with putting info on how I resolved this issue.
For me the issue was the Array to populate the table had 0 rows so cellForRowAtIndexPath was never called.
Make sure that the Array you are using to populate the table has data in it.

UITableView and Selecting Items

I am currently creating a simple grouped UITableView that when the user selects for example "Apple" I would like a image I have in my project to be loaded into a Image View of a Apple.
I have seen some examples on the internet but I am trying to see what else is out there.
Any suggestions would be greatly appreciated. Thanks.
Either set the cell.imageView.highlightedImage, or in the didSelectRowAtIndexPath method, change the cell.imageView.image from nil to some [UIImage imageNamed:#"myImage.png"]:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kCustomCellID = #"com.me.foo.cell";
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
cell.textLabel.highlightedTextColor = [UIColor blueColor];
cell.imageView.image = nil;
cell.imageView.highlightedImage = [UIImage imageNamed:#"myImage.png"];
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(iPadRootViewControllerTableCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Do this if you didnt set the highlightedImage in cellForRowAtIndexPath
// [self tableView:tableView cellForRowAtIndexPath:indexPath].imageView.image = [UIImage imageNamed:#"myApple.png"];
}

Remove Gray UITableView Index Bar

I am making an application with a UITableView that has a few sections (2), and when I run, the table view has this annoying gray index bar on the side, like the one in the "iPod" application, that has but 2 options in it. My question is, how do I hide the "index bar," because it is an unnecessary waste of space?
Example:
Code snippets:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [sections count];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return sections;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return 2;
}
return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sections objectAtIndex:section];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
cell.textLabel.text = [content objectAtIndex:(indexPath.row + [[sectionAmounts objectAtIndex:indexPath.section] intValue])];
tableView.showsVerticalScrollIndicator = NO;
return cell;
}
- (void)viewDidLoad {
[super viewDidLoad];
content = [NSArray arrayWithObjects:#"Sphere", #"Cylinder", #"Circle", nil];
sections = [NSArray arrayWithObjects:#"3d", #"2d", nil];
sectionAmounts = [NSArray arrayWithObjects:[NSNumber numberWithInt:0], [NSNumber numberWithInt:2], nil]; //Second number is objects in first section... odd huh?
self.tableView.showsVerticalScrollIndicator = NO;
[content retain];
[sections retain];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
(Mind my odd comments...)
HiGuy
I tried this, and it didn't work for me.
so i went through the table view properties, and got this.
self.tableView.showsVerticalScrollIndicator = NO;
works like a charm.
*for any one who wants to do this in the future.
That "scroll bar" is your index bar, assuming you're talking about the giant grey thing.
Return nil from sectionIndexTitlesForTableView: and it'll go away.
I had similar issue, however had to deal with my header/footer. Essentially I just removed the following methods
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return #" "; //#"Top";
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
return #" "; //#"Bottom";
}
You just use the below code and gray bar will go....
tableViewBrowse.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
Use sectionIndexBackgroundColor property of UITableView to set the color of index bar to clear color as hiding scroll bar is going to hide the indexes as well.
Add it to your viewDidLoad: as following:
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.sectionIndexBackgroundColor = [UIColor clearColor]; //Replace it with your desired color
}