insertRowsAtIndexPaths custom style - ios

I am trying to create a collapse table like this
My code :
- (WordListTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"wordListTableCell";
WordListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[WordListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSDictionary *uu = [wordList objectAtIndex:indexPath.row];
if(!addingNewCellFlag)
{
if([[[Singleton sharedInstance] currentLaguage] isEqualToString:#"en"])
{
cell.textLabel.text = [uu valueForKey:#"tiitle_en"];
}
else if([[[Singleton sharedInstance] currentLaguage] isEqualToString:#"ru"])
{
cell.textLabel.text = [uu valueForKey:#"tiitle_ru"];
}
UIImage *buttonImage;
if(indexPath.row==0)
{
buttonImage = [[UIImage imageNamed:#"rowFirst.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 5)];
}
else
{
buttonImage = [UIImage imageNamed:#"rowMiddle.png"];
}
cell.backgroundView = [[UIImageView alloc] initWithImage:buttonImage];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.isCanExpanded = TRUE;
}
else
{
if([[[Singleton sharedInstance] currentLaguage] isEqualToString:#"en"]){
cell.textLabel.text = [uu valueForKey:#"content_en"];
}
else if([[[Singleton sharedInstance] currentLaguage] isEqualToString:#"ru"])
{
cell.textLabel.text = [uu valueForKey:#"content_ru"];
}
cell.backgroundColor = [UIColor colorWithRed:253/255.0 green:252/255.0 blue:222/255.0 alpha:1];
cell.textLabel.textColor = [UIColor blackColor];
cell.textLabel.textAlignment = NSTextAlignmentJustified;
cell.isCanExpanded = FALSE;
}
[cell setIsExpanded:FALSE];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
WordListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
addingNewCellFlag = TRUE;
if(cell.isCanExpanded)
{
if(![cell isExpanded]){
[cell setIsExpanded:TRUE];
NSDictionary *uu = [wordList objectAtIndex:indexPath.row];
[wordList insertObject:uu atIndex:indexPath.row+1];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0]]
withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
}
else if ([cell isExpanded])
{
[cell setIsExpanded:FALSE];
[wordList removeObjectAtIndex:indexPath.row+1];
[self.tableView beginUpdates];
NSIndexPath * nextIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:nextIndexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
}
}
cell = nil;
}
It works, if we click on cell we create disruption cell, is the new cell has right text ([uu valueForKey:#"content_en"]), but have wrong backgroundColor (cell.backgroundView = [[UIImageView alloc] initWithImage:buttonImage];). But sometimes the backgroundColor is right ([UIColor colorWithRed:253/255.0 green:252/255.0 blue:222/255.0 alpha:1]).
Please, tell me, how does this method works.

I don't see your code in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
Maybe it's wrong when you deal with the cells of different indexpaths.

Related

get dynamic UIWebview content height of a expand/collapse UITableView in iOS

I am loading a UIWebview in a expand/collapse UITableView. I need to change the row height according to the UIWebview content height. if i set the UIWebview delegate in the UITableview, the UIWebview delgate method keeps get calling over and over. i am calling the webviewDidFinishLoad method to get the content height. Any kind of help/suggestion would be very appreciative.
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.restauRantMenuArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self tableView:self.restaurantMenuTableView canCollapseSection:section])
{
if ([expandedSections containsIndex:section])
{
return 2; // return rows when expanded
}
return 1; // only top row showing
}
// Return the number of rows in the section.
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:self.restaurantMenuTableView canCollapseSection:indexPath.section])
{
if (indexPath.row == 0)
{
static NSString *MyIdentifier = #"menuTitleCell";
RestaurantMenuTitleTableViewCell *cell =(RestaurantMenuTitleTableViewCell*) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[RestaurantMenuTitleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"RestaurantMenuTitleTableViewCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
RestaurantMenuItemObject *object = [self.restauRantMenuArray objectAtIndex:indexPath.section];
cell.titleWebView.opaque = NO;
cell.titleWebView.backgroundColor = [UIColor clearColor];
[cell.titleWebView loadHTMLString:object.menuTitle baseURL:nil];
cell.titleWebView.scrollView.scrollEnabled = NO;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
else
{
static NSString *MyIdentifier = #"menuContentCell";
RestaurantMenuContentTableViewCell *cell =(RestaurantMenuContentTableViewCell*) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[RestaurantMenuContentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"RestaurantMenuContentTableViewCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
RestaurantMenuItemObject *object = [self.restauRantMenuArray objectAtIndex:indexPath.section];
cell.contentWebView.tag = indexPath.section + 1000;
cell.contentWebView.opaque = NO;
cell.contentWebView.backgroundColor = [UIColor clearColor];
[cell.contentWebView loadHTMLString:object.menuContent baseURL:nil];
//cell.contentWebView.scrollView.delegate = self;
[cell.contentWebView.scrollView setShowsHorizontalScrollIndicator:NO];
// cell.contentWebView.scrollView.scrollEnabled = NO;
//cell.contentWebView.delegate = self;
if([[self.imageHeightArray objectAtIndex:indexPath.section] isEqualToString:#"150"])
{
//cell.contentWebView.delegate = self;
}
// first row
//cell.textLabel.text = #"Expandable"; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
//cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
else
{
//cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown]
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor clearColor];
return cell;
}
}
else
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.backgroundColor = [UIColor clearColor];
return cell;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
RestaurantMenuItemObject *object = [self.restauRantMenuArray objectAtIndex:indexPath.section];
UIWebView *thisWebView = (UIWebView*)[self.restaurantMenuTableView viewWithTag:indexPath.section+1000];
[thisWebView loadHTMLString:object.menuContent baseURL:nil];
thisWebView.delegate = self;
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
//if there is any previous selected index
//if selected index is not the previous selected
if (selectedIndex && (selectedIndex.section != indexPath.section)) {
[self collapseOrExpandForIndexPath:selectedIndex inTableView:tableView];
}
if ([selectedIndex isEqual:indexPath]) {
selectedIndex = nil;
}
else{
selectedIndex = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
}
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
[self collapseOrExpandForIndexPath:indexPath inTableView:tableView];
if (indexPath.row == 0) {
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
}
}
- (void)collapseOrExpandForIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView{
if (!indexPath.row)
{
// only first row toggles exapand/collapse
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}
else
{
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
if (currentlyExpanded)
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
else
{
//RestaurantMenuItemObject *object = [self.restauRantMenuArray objectAtIndex:indexPath.section];
// UIWebView *thisWebView = (UIWebView*)[self.restaurantMenuTableView viewWithTag:indexPath.section+1000];
//
// [thisWebView loadHTMLString:object.menuContent baseURL:nil];
//
// thisWebView.delegate = self;
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//return UITableViewAutomaticDimension;
if(indexPath.row == 0)
return 50.00;
else
{
return 240;//[[self.imageHeightArray objectAtIndex:indexPath.section] integerValue];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 1.00;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 1.00;
}
pragma mark Table View Delegate Method ends
Create a class level property (CGFloat),say webViewHeight to track web view's height.
On table view didSelectRowAtIndexPath method load url in web view.
Calculate web view height in webviewDidFinishLoad delegate method of web view and set it in class level height variable,webViewHeight. After calculating height call [tableView reloadData];
Set selected cell height with webViewHeight and rest with default,say 44.0 in heightForRowAtIndexPath method of data source.
IMP: Set maximum web view height also if calculated height exceed max height set calculated height to max height. And enable web view scrolling so that user is able to view all web view content.

Expandable UITableViewCell overlapping other cells

I'm working on a UITableView with expandable cells and I got it working with:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if(_selectedCellIndexPath != nil
&& [_selectedCellIndexPath compare:indexPath] == NSOrderedSame)
return 160;
return 40;
}
and
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_selectedCellIndexPath = indexPath;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
And the UITableViewCell set up in Storyboard as:
But when I change it to this:
to add the description and button, it scrambles up everything like this:
How come the description textview and more info button are showing even though the heightForRowAtIndexPath is 40 and they should be 'hidden'?
Or am I taking a wrong approach to this?
Also, the tapping and expanding is not applied to the searchDisplayController.searchResultsTableView. How can I do this?
Edit: cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"IngredientCell";
UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.backgroundColor = [UIColor colorWithRed:1.000 green:1 blue:1 alpha:0.333];
cell.tintColor = [UIColor whiteColor];
UILabel *title = (UILabel*) [cell viewWithTag:1];
UILabel *summary = (UILabel*) [cell viewWithTag:2];
UIButton *moreInfo = (UIButton*) [cell viewWithTag:3];
summary.hidden = YES;
moreInfo.hidden = YES;
[title setTextColor: [UIColor whiteColor]];
// Display recipe in the table cell
if (tableView == self.searchDisplayController.searchResultsTableView) {
[title setText: [searchResults objectAtIndex:indexPath.row]];
//set summary
} else {
[title setText: [ingredients objectAtIndex:indexPath.row]];
//set summary
}
// Change color if dissallowed
if ([[title text] rangeOfString:#"Egg"].location != NSNotFound) {
cell.backgroundColor = [UIColor colorWithRed:1.000 green:0.350 blue:0.485 alpha:0.333];
}
// Change color when selected
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor clearColor];
cell.selectedBackgroundView = customColorView;
return cell;
}

Fetching the checkmarked cell's label

I am working with the table view. I added the checkmark Accessory on the first tap of the screen and removed this checkmark on the second tap. I added few ckeckmarks on the cells of table view. Now i want that the labels of the cells having the checkmarks should be displayed on the NSlog.
please help me out regarding this issue. Any help will be much appriciable.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView.tag == 0)
{
return [celltitles count];
}
else
{
return 7;
}
}
- (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];
}
if (tableView.tag == 0)
{
cell.textLabel.text = [celltitles objectAtIndex:indexPath.row];
if (indexPath.row == 0)
{
habitname = [[UITextField alloc]initWithFrame:CGRectMake(150, 0, 150, 50)];
habitname.placeholder = #"Habit Name";
habitname.delegate= self;
[cell addSubview:habitname];
}
else if (indexPath.row == 1)
{
timelbl = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 50)];
timelbl.text = #"OFF";
timelbl.textAlignment = NSTextAlignmentCenter;
[cell addSubview:timelbl];
timetitlelbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
timetitlelbl.text = #"Alert";
timetitlelbl.textAlignment = NSTextAlignmentCenter;
[cell addSubview:timetitlelbl];
toggleswitch = [[UISwitch alloc] initWithFrame:CGRectMake(250, 5, 50, 60)];
toggleswitch.on = NO;
[toggleswitch addTarget:self action:#selector(toggleSwitch) forControlEvents:(UIControlEventValueChanged | UIControlEventTouchDragInside)];
[cell addSubview:toggleswitch];
}
}
else if (tableView.tag == 1)
{
cell.textLabel.text = [daysarray objectAtIndex:indexPath.row];
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 1)
{
if (toggleswitch.on)
{
[self datepickershown:timelbl.text animated:YES];
if (self.datePickerIsShowing)
{
//[self datepickershown];
//[self hideDatePickerCell];
[dscptxt resignFirstResponder];
}
else
{
[dscptxt resignFirstResponder];
[self.timelbl resignFirstResponder];
[self showDatePickerCell];
}
}
else
{
timelbl.textColor = [UIColor grayColor];
}
}
else if (indexPath.row > 2 && indexPath.row <10)
{
NSLog(#"I am Selectin the row");
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
// NSLog(#"Selected Accessory Is %d",cell.accessoryType);
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
[self.tableview deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)savedata:(id)sender
{
}
Above is the code which i am using and on the save action i want the log.
Don't use the UITableView to store your data. Cells are reused, so that's not a reliable way to detect which items you have selected.
You could store whether an item is selected in an array, for instance. Then in your cellForRowAtIndexPath determine if the checkmark should be displayed. In didSelectRowAtIndexPath you update the model (your array) and request a reload for the specific cell.
This will result in a better MVC separation.
EDIT: added example for the UITableView stuff
// for this example we'll be storing NSIndexPath objects in our Model
// you might want to use a #property for this
NSMutableSet *model = [NSMutableSet set];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
if([model containsObject:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
...
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
// update the model
if([model containsObject:indexPath]) {
[model removeObject:indexPath];
}
else {
[model addObject:indexPath];
}
// request reload of selected cell
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation: UITableViewRowAnimationFade];
...
}
Now it should be fairly easy to log all selected items, without having to use the UITableView: it's all in your model now!
Make a for loop:
NSMutableArray *mutArray = [[NSMutableArray alloc] init];
for(i = 0;i <= self.rowCount-1;i++)
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
[mutArray addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
}
NSLog(#"Array: %#", mutArray);

How to store UITableViewCell

I need to get indexPath of cell to delete but my app has auto reload after 2s to check new file so indexpath has changed so I don't get it correctly. Now, I want get cell but I don't know how to store cell. This is my codes:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//[_tableView clearsContextBeforeDrawing];
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.tag = indexPath.row;
if([FileNameArray count] != 0){
CGRect frame = CGRectMake(10, 05, 100, 20);//(20, 0, 80, 40);
UILabel *lbl1 = [[UILabel alloc]initWithFrame:frame];
[lbl1 setFont:[UIFont fontWithName:#"Helvetica" size:15.0]];
[lbl1 setTextColor:[UIColor blackColor]];
[lbl1 setTextAlignment:UITextAlignmentLeft];
lbl1.text = [FileNameArray objectAtIndex:indexPath.row];
[cell addSubview:lbl1];
[lbl1 release];
}
return cell;
}
removeCell function:
-(void) removeCell:(NSIndexPath *)indexPath
{
[_tableView beginUpdates];
[_tableView deleteRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
// [_tableView reloadData];
[_tableView endUpdates];
}
Do you have suggestions?

How to add images to UITableView cell?

I temporarly added some values to the UITableViewCell programmatically. But I need to add images to each cell. How can I do that?
Here is my code. .h file
#interface BidalertsViewController : UIViewController <UITableViewDelegate,UITableViewDataSource> {
NSArray *listData;
}
#property(nonatomic, retain) NSArray *listData;
#end
.m file
#synthesize listData;
- (void)viewDidLoad {
UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(5,0,310,28)];
newView.backgroundColor=[UIColor whiteColor];
UITextView *mytext = [[UITextView alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 25.0)];
mytext.backgroundColor = [UIColor clearColor];
mytext.textColor = [UIColor blackColor];
mytext.editable = NO;
mytext.font = [UIFont systemFontOfSize:15];
mytext.text = #"Asset Name";
[mytext release];
[newView addSubview:mytext];
[self.view addSubview:newView];
[newView release];
NSArray *array = [[NSArray alloc] initWithObjects:#"iPhone", #"iPod", #"iPad",nil];
self.listData = array;
[array release];
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[listData dealloc];
[super dealloc];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:#"user.jpg"];
[cell.contentView addSubview:imv];
[imv release];
}
#end
The code didn't add images to the cell. What's the problem? How can I do to add custom image to cell?
Move return cell; at the end of the method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:#"user.jpg"];
[cell.contentView addSubview:imv];
[imv release];
return cell;
}
You can add images using the imageView property of a cell:
cell.imageView.image = [UIImage imageNamed:#"user.jpg"];
in your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method.
Here's an example cell loading a facebook image in a table cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
// Leave cells empty if there's no data yet
if (nodeCount > 0)
{
// Set up the cell...
AppRecord *appRecord = [self.friendsList objectAtIndex:indexPath.row];
cell.textLabel.text = friend.name;
// Only load cached images; defer new downloads until scrolling ends
if (!appRecord.icon)
{
// set the url
appRecord.imageURLString = [NSString stringWithFormat:#"http://graph.facebook.com/%#/picture", friend.recordID];
// request the download
if (self.tableView.dragging == NO && self.tableView.decelerating == NO)
{
[self startIconDownload:appRecord forIndexPath:indexPath];
}
// if a download is deferred or in progress, return a placeholder image
cell.imageView.image = [UIImage imageNamed:#"Placeholder.png"];
}
else
{
cell.imageView.image = appRecord.icon;
}
}
return cell;
you adding it right, but you fogot one thing:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row]; cell.textLabel.text = [listData objectAtIndex:row];
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:#"user.jpg"];
[cell.contentView addSubview:imv];
[imv release];
//you fogot this:
return cell;
}
// create a rectangle box for image view
UIImageView *iconImage = [[UIImageView alloc] init];
iconImage.frame = CGRectMake(12,4,53.5,53.5);
// Create a label for cells
UILabel *cellName = [[UILabel alloc] initWithFrame:CGRectMake(75,18,200,20)];
cellName.font = [self fontForBodyTextStyle];
NSString *cellNameStr = [NSString stringWithFormat:#"%#",self.tableCellNames[indexPath.row]];
// Select path row tab actions
switch (indexPath.row) {
case 0:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"condition.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
case 1:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"videos.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
case 2:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"provider.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
case 3:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"info.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
default:
NSAssert(NO, #"Unhandled value in cellForRowAtIndexPath");
break;
}
Thank VKJ,

Resources