UITableView Cell is regenerating - iphone

I have UITableViewCell with UILabel and UISwitch. By default all UISwitch is set to off.
Once I will turn on the switch and then scroll through table the switch value is set to default again,i.e.Off
Below is the code which I have used:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell != nil) cell = nil;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if (indexPath.row == 0) {
UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 30)];
lbl1.text = #"Some Text";
[cell addSubview:lbl1];
switch = [[UISwitch alloc] initWithFrame:CGRectMake(190, 10, 200, 30)];
[switch setOn:NO];
switch.tag = 1;
[switch addTarget:self action:#selector(switchTapped:) forControlEvents:UIControlEventChanged];
[cell addSubview:switch];
}
}
// Below is my switchTapped method:
- (void) switchTapped: (id)sender {
UISwitch *tapSwitch = (UISwitch *)sender;
switch (tapSwitch.tag) {
case 1:
if (tapSwitch.on) {
// do something
}
else {
// do something
}
break;
case 2:
if (tapSwitch.on) {
// do something
}
else {
// do something
}
break;
}
Am I doing anything wrong over here?
Thank You.

You're using really nasty code which regenerates the cell each time it's needed:
if(cell != nil)
{
cell = nil;
}
if (cell == nil)
{
...
}
Do you bind the state of your switch to some retained object (e.g. Item model object, where single cell reflects an Item)?

This is how I write my cell drawing code:
Basically, within my if(cell == nil) { ... } I do all the "initWithFrame". Anything outside that, I simply set the value such as label text. Don't do the initWithFrame outside the if(cell == nil) {...} block of code.
-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath
{
static NSString *reusableCell = #"reusableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusableCell];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusableCell] autorelease];
thumbnail = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 106, 81)];
feedTitle = [[UILabel alloc] initWithFrame:CGRectMake(116, 3, [IOSDevice screenWidth] - 140, 25)];
postDate = [[UILabel alloc] initWithFrame:CGRectMake(116, 10, [IOSDevice screenWidth] - 140, 50)];
description = [[UILabel alloc] initWithFrame:CGRectMake(116, 45, [IOSDevice screenWidth] - 140, 50)];
// setting tag reminders so we can identify the element to replace
[thumbnail setTag:1];
[feedTitle setTag:2];
[postDate setTag:3];
[description setTag:4];
[[cell contentView] addSubview:thumbnail];
[[cell contentView] addSubview:feedTitle];
[[cell contentView] addSubview:description];
[[cell contentView] addSubview:postDate];
[thumbnail release];
[feedTitle release];
[description release];
[postDate release];
}
thumbnail = (UIImageView *)[[cell contentView] viewWithTag:1];
feedTitle = (UILabel *)[[cell contentView] viewWithTag:2];
postDate = (UILabel *)[[cell contentView] viewWithTag:3];
description = (UILabel *)[[cell contentView] viewWithTag:4];
[feedTitle setBackgroundColor:[UIColor clearColor]];
[feedTitle setFont:[UIFont fontWithName:#"Helvetica-Bold" size:16]];
[feedTitle setTextColor:[UIColor colorWithRed:0.215 green:0.215 blue:0.215 alpha:1.0]];
[description setBackgroundColor:[UIColor clearColor]];
[description setFont:[UIFont fontWithName:#"Helvetica" size:12]];
[description setTextColor:[UIColor colorWithRed:0.328 green:0.328 blue:0.328 alpha:1.0]];
[description setNumberOfLines:2];
[description setLineBreakMode:UILineBreakModeWordWrap];
[postDate setBackgroundColor:[UIColor clearColor]];
[postDate setFont:[UIFont fontWithName:#"Helvetica" size:12]];
[postDate setTextColor:[UIColor colorWithRed:0.707 green:0.180 blue:0.141 alpha:1.0]];
[thumbnail setImage:[[items objectAtIndex:[indexPath row]] objectForKey:#"thumb"]];
[feedTitle setText:[[items objectAtIndex:[indexPath row]] objectForKey:#"title"]];
[description setText:[[items objectAtIndex:[indexPath row]] objectForKey:#"summary"]];
// Format date
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[postDate setText:[dateFormatter stringFromDate:[[items objectAtIndex:[indexPath row]] objectForKey:#"date"]]];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
if([feedList contentOffset].y < -50)
{
shouldUpdate = TRUE;
[activityIndicator stopAnimating];
[feedList setContentOffset:CGPointMake(0, -30) animated:NO];
[self loadData];
loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -25, [IOSDevice screenWidth], 20)];
[loadingLabel setText:#"Loading New Data"];
[loadingLabel setTextAlignment:UITextAlignmentCenter];
[loadingLabel setBackgroundColor:[UIColor clearColor]];
[loadingLabel setTextColor:[UIColor colorWithRed:0.215 green:0.215 blue:0.215 alpha:1.0]];
[loadingLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:14]];
reloadingSpinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(70, -25, 20, 20)];
[reloadingSpinner setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[reloadingSpinner startAnimating];
[reloadingSpinner setHidesWhenStopped:YES];
[feedList addSubview:reloadingSpinner];
[feedList addSubview:loadingLabel];
}
return cell;
}

Related

How to display UILabel when UIImage is not present

I have a UITableView where I am loading images from the sever. But sometimes there are no images to display on the UITableView and at that I want to display UILabel. Wondering how would I accomplish this. I would appreciate any help or code snippets to achieve this.
Thank you very much!
I tried what you said. Everything works fine for the first time when you load the table, but as soon as you start scrolling all the labels and button go all over the places.
Here is my code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if (msgImgFile){
NSLog (#"Image file found!");
lblOne = [[UILabel alloc] initWithFrame:CGRectMake(10, 360, 200, 20)];
lblTwo = [[UILabel alloc] initWithFrame:CGRectMake(10, 378, 150, 20)];
lblThree = [[UILabel alloc] initWithFrame:CGRectMake(10, 398, 150, 20)];
btnPlayStop.frame = CGRectMake(255.0f, 375.0f, 30.0f, 30.0f);
}
else
{
NSLog(#"Image file not found. Simply load the UILabel and UIButton");
lblOne = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 200, 20)];
lblTwo = [[UILabel alloc] initWithFrame:CGRectMake(10, 68, 150, 20)];
lblThree = [[UILabel alloc] initWithFrame:CGRectMake(10, 88, 150, 20)];
btnPlayStop.frame = CGRectMake(255.0f, 45.0f, 30.0f, 30.0f);
}
lblOne.font = [UIFont fontWithName:#"Arial" size:12];
[lblOne setBackgroundColor:[UIColor clearColor]];
lblOne.tag = 1;
lblTwo.font = [UIFont fontWithName:#"Arial" size:12];
[lblTwo setBackgroundColor:[UIColor clearColor]];
lblTwo.tag = 2;
lblThree.font = [UIFont fontWithName:#"Arial" size:10];
[lblThree setBackgroundColor:[UIColor clearColor]];
lblThree.tag = 3;
lblFour = [[UILabel alloc] initWithFrame:CGRectMake(10, 24, 150, 20)];
lblFour.font = [UIFont fontWithName:#"Arial" size:12];
[lblFour setBackgroundColor:[UIColor clearColor]];
lblFour.tag = 4;
btnPlayStop = [UIButton buttonWithType:UIButtonTypeCustom];
[btnPlayStop setTitle:#"Play" forState:UIControlStateNormal];
[btnPlayStop setImage:[UIImage imageNamed:#"Play Button.png"] forState:UIControlStateNormal];
[btnPlayStop addTarget:self action:#selector(playRecordClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:lblOne];
[cell addSubview:lblTwo];
[cell addSubview:lblThree];
[cell addSubview:lblFour];
[cell.contentView addSubview:btnPlayStop];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(queue, ^{
msgObjImg = (PFObject *)[self.imageDataMutArray objectAtIndex:indexPath.row];
createdDt = msgObjImg.createdAt;
msgImgFile = [msgObjImg objectForKey:#"siqImage"];
NSData *imgData = [msgImgFile getData];
UIImage *msgImgFound = [UIImage imageWithData:imgData];
UIImage *newImg = [self scaleImage:msgImgFound toSize:CGSizeMake(280.0, 300.0)];
dispatch_sync(dispatch_get_main_queue(), ^{
UILabel *dtTimeLabel = (UILabel *)[cell viewWithTag:3];
NSDateFormatter *dtFormat = [[NSDateFormatter alloc]init];
[dtFormat setDateFormat:#"MM-dd-yyyy HH:mm"];
[dtFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-18000]];
NSString *createdDtString = [dtFormat stringFromDate:createdDt];
dtTimeLabel.text = [NSString stringWithFormat:#"Received on: %#",createdDtString];
[[cell imageView] setImage:newImg];
[cell setNeedsLayout];
}
return cell;
}
I can see where the problem is, and can tell you the right procedure to solve this.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
lblOne = [[UILabel alloc]init];
lblOne.tag = 1;
lblTwo = [[UILabel alloc]init];
lblTwo.tag = 2;
lblThree = [[UILabel alloc]init];
lblThree.tag = 3;
lblFour = [[UILabel alloc]init];
lblFour.tag = 4;
btnPlayStop = [[UILabel alloc]init];
btnPlayStop.tag = 5;
// Perform addition functions ( your requirements )
[cell.contentView addSubview:lblOne];
[cell.contentView addSubview:lblTwo];
[cell.contentView addSubview:lblThree];
[cell.contentView addSubview:lblFour];
[cell.contentView addSubview:btnPlayStop];
}
else
{
lblOne = (UILabel*)[cell.contentView viewWithTag:1];
lblTwo = (UILabel*)[cell.contentView viewWithTag:2];
lblThree = (UILabel*)[cell.contentView viewWithTag:3];
lblFour = (UILabel*)[cell.contentView viewWithTag:4];
btnPlayStop = (UILabel*)[cell.contentView viewWithTag:5];
// AND SO ON ...
}
// SET THE VALUES HERE FOR YOUR CONTENT VALUES
return cell;
}
You need to create the cells using dynamic content views.
Try the above snippet, and modify according to your own..
In your cellForRowAtIndexPath method
UIImage *image = [imagesArray objectAtIndex:indexPath.row];
if (image) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:yourImageViewFrame];//create desired Frame
imageView.image = image;
[cell addSubview:imageView];
} else {
UILabel *label = [[UILabel alloc] initWithFrame:yourLabelFrame];//create desired frame
label.text = #"No Image";
[cell addSubview:label];
}
When your images are finished loading from the server, call [tableView reloadData];

UITableView reload

I am facing some problem in reloading the table. My cellForRowAtIndexPath is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int counter=indexPath.row;
NSString *CellIdentifier = [NSString stringWithFormat:#"%d",counter];
// Dequeue or create a cell of the appropriate type.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
//ID
UILabel *lblID=[[UILabel alloc]init];
lblID.frame=CGRectMake(10, 15.0, 150, 30.0);
[lblID setFont:[UIFont boldSystemFontOfSize:20.0]];
[lblID setBackgroundColor:[UIColor clearColor]];
[lblID setTextColor:[UIColor blackColor]];
lblID.text = [arrID objectAtIndex:indexPath.row];
[cell.contentView addSubview:lblID];
[lblID release];
//Date
UILabel *lblName=[[UILabel alloc]init];
lblName.frame=CGRectMake(130, 15.0, 250, 30.0);
[lblName setFont:[UIFont systemFontOfSize:20.0]];
[lblName setBackgroundColor:[UIColor clearColor]];
[lblName setTextColor:[UIColor blackColor]];
lblName.text = [arrProductName objectAtIndex:indexPath.row];
[cell.contentView addSubview:lblName];
[lblName release];
//Qty
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(320, 20, 50, 30)];
[textField addTarget:self action:#selector(TextOfTextField:)
forControlEvents:UIControlEventEditingDidEnd];
textField.userInteractionEnabled = true;
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.text = [arrItems objectAtIndex:indexPath.row];
textField.tag = indexPath.row;
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypePhonePad;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.delegate = self;
[arrTxtItems addObject:textField];
[cell.contentView addSubview:textField];
[textField release];
//Discount
UITextField *txtDiscount = [[UITextField alloc] initWithFrame:CGRectMake(460, 20, 50, 30)];
// [txtDiscount addTarget:self action:#selector(TextOfTextField:)
// forControlEvents:UIControlEventEditingDidEnd];
txtDiscount.userInteractionEnabled = true;
txtDiscount.borderStyle = UITextBorderStyleRoundedRect;
txtDiscount.font = [UIFont systemFontOfSize:15];
txtDiscount.text = [arrDiscount objectAtIndex:indexPath.row];
txtDiscount.tag = indexPath.row;
txtDiscount.autocorrectionType = UITextAutocorrectionTypeNo;
txtDiscount.keyboardType = UIKeyboardTypePhonePad;
txtDiscount.returnKeyType = UIReturnKeyDone;
txtDiscount.clearButtonMode = UITextFieldViewModeWhileEditing;
txtDiscount.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txtDiscount.delegate = self;
[arrTxtDiscount addObject:txtDiscount];
[cell.contentView addSubview:txtDiscount];
[txtDiscount release];
//Price
UILabel *lblPrice=[[UILabel alloc]init];
lblPrice.frame=CGRectMake(560, 15.0, 250, 30.0);
[lblPrice setFont:[UIFont boldSystemFontOfSize:20.0]];
[lblPrice setBackgroundColor:[UIColor clearColor]];
[lblPrice setTextColor:[UIColor blackColor]];
[arrLblNetPrice addObject:lblPrice];
NSString *strPrice = [arrPrice objectAtIndex:indexPath.row];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setGroupingSeparator:#"."];
[formatter setGroupingSize:2];
[formatter setUsesGroupingSeparator:YES];
[formatter setSecondaryGroupingSize:3];
NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[strPrice doubleValue]]];
[formatter release];
NSLog(#"str : %#",str);
NSLog(#"strPrice : %#",strPrice);
lblPrice.text = str;
[cell.contentView addSubview:lblPrice];
[lblPrice release];
}
return cell;
}
Structuring the cell this way helps me preserve the values of textFields when I scroll the table. But at some point when I reload the table control does not fall in the if condition because the cell has not been released yet. Where should I release the cell in this condition?
You need to separate creating/acquiring the cell instance from configuring the cell properties with data. Change your code as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int counter=indexPath.row;
NSString *CellIdentifier = [NSString stringWithFormat:#"%d",counter];
// Dequeue or create a cell of the appropriate type.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
//ID
UILabel *lblID=[[UILabel alloc]init];
lblID.frame=CGRectMake(10, 15.0, 150, 30.0);
[lblID setFont:[UIFont boldSystemFontOfSize:20.0]];
[lblID setBackgroundColor:[UIColor clearColor]];
[lblID setTextColor:[UIColor blackColor]];
lblID.tag = MyViewTagIDLabel; // make an enum to give your subviews unique tags > 0
[cell.contentView addSubview:lblID];
[lblID release];
// add the rest of your subviews
// any other cell configuration that does not change based on the ind
}
// configure the cell with data based on the indexPath
UILabel lblID = [cell.contentView viewWithTag:MyViewTagIDLabel];
lblID.text = [arrID objectAtIndex:indexPath.row];
// configure the rest of the subviews
return cell;
}

problem with table view grouped table view

tableview problem: i am using 3 uilable for displaying productname, some description and image. all data displayed but when scrolling the table the labels are filled with another text with the actual text.. how can we handle this?
Code:
- (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];
}
UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(2, 2, 41, 41)];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
NSDictionary *aDict1 = [[NSDictionary alloc]init];
aDict1 = [tableData objectAtIndex:indexPath.row];
NSString *prdStus = [aDict1 objectForKey:#"ProductStatus"];
NSLog(#"product status is %# ",prdStus);
if ([prdStus isEqualToString:#"Orange"]) {
[imageview setImage:[UIImage imageNamed:#"Yellow.png"]];
}
if ([prdStus isEqualToString:#"Green"]) {
[imageview setImage:[UIImage imageNamed:#"Green.png"]];
}
if ([prdStus isEqualToString:#"Red"]) {
[imageview setImage:[UIImage imageNamed:#"Red.png"]];
}
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(46, 0, 220, 12) ];
label2.font = [UIFont systemFontOfSize:12];
label2.text = #"";
if (indexPath.row <[tableData count]) {
label2.text = [aDict1 objectForKey:#"ProductName"];
}
[cell addSubview:label2];
[cell addSubview:imageview];
label2.backgroundColor =[UIColor clearColor];
UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(46, 13, 220, 30) ];
label3.font = [UIFont systemFontOfSize:10];
label3.text = #"";
label3.text = [aDict1 objectForKey:#"ProductDescription"];
[cell addSubview:label3];
return cell;
}
please tell me how to avoid this..
Grouped Table view.
Here is also i am facing same problem.
I am using 4 section
1st and 3rd sections 1 row each,
2nd sec 3 rows,
4th sec 5
when configure the text the first section label displayed on 4th and 3rd section data also displayed on 4th section.
Code
- (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];
}
cell.userInteractionEnabled =NO;
if (indexPath.section == 0)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 2, 294, 40) ];
label.backgroundColor = [UIColor clearColor];
NSDictionary *aDict1 = [[NSDictionary alloc]init];
aDict1 = [detailsArray objectAtIndex:0];
label.text=#"";
label.text =[aDict1 objectForKey:#"ProductName"];
label.numberOfLines = 2;
label.lineBreakMode = UILineBreakModeWordWrap;
[cell addSubview:label];
[label release];
// [cell addSubview:imgview1];
// [imgview1 release];
}
if (indexPath.section ==1 ) {
if (indexPath.row == 0)
{
imgview = [[UIImageView alloc]initWithFrame:CGRectMake(255,2 , 46, 46)];
[cell addSubview:imgview];
[imgview release];
cell.textLabel.text = #"Actual Halal Rating";
NSDictionary *aDict1 = [[NSDictionary alloc]init];
aDict1 = [detailsArray objectAtIndex:0];
NSString *statStr=[[NSString alloc] init];
statStr = [aDict1 objectForKey:#"ProductHalalStatus"];
NSLog(#"status is %#",statStr);
imgview1 = [[UIImageView alloc]initWithFrame:CGRectMake(255,2 , 20, 20)];
if ([statStr isEqualToString:#"Red"]) {
[imgview1 setImage:[UIImage imageNamed:#"Red.png"]];
}
if ([statStr isEqualToString:#"Orange"] ) {
[imgview1 setImage:[UIImage imageNamed:#"Yellow.png"]];
}
if ([statStr isEqualToString:#"Green"]) {
[imgview1 setImage:[UIImage imageNamed:#"Green.png"]];
}
[cell addSubview:imgview1];
[imgview1 release];
}
if (indexPath.row == 1) {
cell.textLabel.text = #"Halal (Permisible)";
[imgview setImage:[UIImage imageNamed:#"Green.png"]];
}
if (indexPath.row == 2) {
cell.textLabel.text = #"Masbooh (Doubtful)";
[imgview setImage:[UIImage imageNamed:#"Yellow.png"]];
}
if (indexPath.row == 3) {
cell.textLabel.text = #"Haram (Not Permisible)";
[imgview setImage:[UIImage imageNamed:#"Red.png"]];
}
}
if (indexPath.section == 2) {
NSDictionary *aDict2 = [[NSDictionary alloc]init];
aDict2 = [detailsArray objectAtIndex:0];
// NSArray *ingrArr =[aDict2 objectForKey:#"IngredientInfo1"];
textview1 =[[UITextView alloc]initWithFrame:CGRectMake(12, 2, 294, 96)];
//textview1.text = ingrStr;
textview1.editable =NO;
[textview1 setFont:[UIFont systemFontOfSize:15]];
[cell addSubview:textview1];
[textview1 release];
}
if (indexPath.section == 3) {
}
return cell;
}
Remove the line, from you code ....
if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
and add the following line
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]

Selected state of UIButton in UITableView

I have UIButton in each cell of UITableView. When I touch it, its state is set to selected. But when I scroll table view so the button isn't visible, the state is set to normal. How can I do it that UIButton remain selected?
Thank you.
Edit: Here is the cellForRowAtIndexPath code:
- (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];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (indexPath.row < [messagesArray count]) {
Zprava *msgObj = [messagesArray objectAtIndex:indexPath.row];
int width = 0;
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
width = 320;
} else {
width = 480;
}
CGSize boundingSize = CGSizeMake(width, CGFLOAT_MAX);
CGSize requiredSize = [msgObj.mmessage sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
UIButton *background = [[UIButton alloc] initWithFrame:CGRectMake(10, 25, 300, requiredSize.height + 20)];
[background setBackgroundImage:[[UIImage imageNamed:#"balloon.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:15] forState:UIControlStateNormal];
[background setBackgroundImage:[[UIImage imageNamed:#"selected-balloon.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:15] forState:UIControlStateSelected];
[background addTarget:self action:#selector(action:) forControlEvents:UIControlEventTouchUpInside];
background.tag = msgObj.msgID;
[[cell contentView] addSubview:background];
[background release];
UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 285, 15)];
[dateLabel setFont:[UIFont systemFontOfSize:12]];
[dateLabel setLineBreakMode:UILineBreakModeWordWrap];
[dateLabel setTextColor:[UIColor lightGrayColor]];
[dateLabel setNumberOfLines:0];
[dateLabel setTextAlignment:UITextAlignmentRight];
[dateLabel setText:msgObj.mdate];
[dateLabel setBackgroundColor:[UIColor clearColor]];
[dateLabel setOpaque:NO];
[[cell contentView] addSubview:dateLabel];
[dateLabel release];
UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 275, requiredSize.height + 5)];
[messageLabel setFont:[UIFont systemFontOfSize:17]];
[messageLabel setLineBreakMode:UILineBreakModeWordWrap];
[messageLabel setTextColor:[UIColor blackColor]];
[messageLabel setNumberOfLines:0];
[messageLabel setText:msgObj.mmessage];
[messageLabel setBackgroundColor:[UIColor clearColor]];
[messageLabel setOpaque:NO];
[[cell contentView] addSubview:messageLabel];
[messageLabel release];
}
return cell;
}
Save button states somewhere in your model separately from table view and set buttons state in cellForRowAtIndexpath: method again.

Cell selection style in iPhone

By default there is three selection style in iPhone - table view.
gray - blue - none.
I don't need gray or blue.
I want to set my custom.
For example, in normal situation a cell should have "aaaa.png" background, and selected cell should have "bbbbb.png" background.
I have tried to apply cell.backgroundView & cell.selectedBackground view. However it isn't working.
Three lines of code here, but you don't need an image!
UIView *selectedBackgroundViewForCell = [UIView new];
[selectedBackgroundViewForCell setBackgroundColor:[UIColor redColor]];
theCell.selectedBackgroundView = selectedBackgroundViewForCell;
Here's one way to do it with only 1 line of code:
cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pink.png"]] autorelease];
obviously you'll need to make the image.
I tried following & it worked.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"%i",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
XML_FitnessPrograms *t=[arrayPrograms objectAtIndex:indexPath.row];
cell=((indexPath.row%2)==0) ?
[self getCellContentView:CellIdentifier program_name:t.program_name alterNate:NO indexPath:indexPath] :
[self getCellContentView:CellIdentifier program_name:t.program_name alterNate:YES indexPath:indexPath] ;
CGRect a=CGRectMake(8, 0, 300, 44);
UIImageView *aImg=[[UIImageView alloc] initWithFrame:a];
UIImageView *bImg=[[UIImageView alloc] initWithFrame:a];
aImg.image=[UIImage imageNamed:#"white-rect-tab.png"]; //arrow.png
bImg.image=[UIImage imageNamed:#"white-rect-tab-copy.png"];
[aImg setContentMode:UIViewContentModeScaleToFill];
[bImg setContentMode:UIViewContentModeScaleToFill];
cell.backgroundView=aImg;
cell.selectedBackgroundView=bImg;
[aImg release];
[bImg release];
}
return cell;
}
-(UITableViewCell*)getCellContentView:(NSString*)cellIdentifier program_name:(NSString*)program_name alterNate:(BOOL)alterNate indexPath:(NSIndexPath*)indexPath
{
UITableViewCell *cell; UILabel *tmp;
CGRect label1Frame=CGRectMake(5, 0, 260, 44);
cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
cell.frame=CGRectMake(8, 0, 280, 44);
cell.backgroundColor=[UIColor clearColor];
tmp=[[UILabel alloc] initWithFrame:label1Frame];
tmp.textColor=[UIColor colorWithRed:(9.0/255.0) green:(68.0/255) blue:(85.0/255) alpha:1.0];
[tmp setFont:[UIFont fontWithName:#"Arial-BoldMT" size:15]];
tmp.text=program_name;
[tmp setShadowColor:[UIColor lightGrayColor]];
tmp.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:tmp]; [tmp release];
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
return cell;
}