Issue With setting tag for Button UITableView - objective-c

I have two buttons inside sectioned tableview cell thumbs up and thumbs down. Initially image of both button is not selected. When I select thumbs up button its image become thumbs up selected and other one become thumbsdown not selected and vice versa.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(#"mod:numberOfSectionsInTableView");
NSLog(#"[preferences count]=%d",[preferences count]);
return [preferences count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.choices count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexpath
{
NSLog(#"cellForRowAtIndexPath: DISPLAY TEST");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
NSLog(#"Text is: %#", [choices objectAtIndex:indexpath.row]);
NSLog(#"CHOICE AT INDEX PATH IS: %#",[choices objectAtIndex:indexpath.row %[choices count]]);
cell.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor blackColor];
// Thumbs up button.
//UIButton *thumbsUp = [[UIButton alloc]init];
thumbsUp = [UIButton buttonWithType:UIButtonTypeCustom];
[thumbsUp setTag:(indexpath.row+(indexpath.section * 50))];
[thumbsUp addTarget:self action:#selector(thumbUp_ButtonClicked:event:)
forControlEvents:UIControlEventTouchUpInside];
[thumbsUp setTitle:#"" forState:UIControlStateNormal];
thumbsUp.frame = CGRectMake(150.0, 20, 20, 15);
[thumbsUp setBackgroundImage:[UIImage imageNamed:#"thumbsup_not_selected.png"]
forState:UIControlStateNormal];
//NSLog(#"------------------>TAG TEST : %d",(indexpath.row+(indexpath.section * 50)));
[cell.contentView addSubview:thumbsUp];
// Thumbs down button
thumbsDown = [UIButton buttonWithType:UIButtonTypeCustom];
[thumbsDown addTarget:self action:#selector(thumbDown_ButtonClicked:event:)
forControlEvents:UIControlEventTouchUpInside];
[thumbsDown setTitle:#"" forState:UIControlStateNormal];
thumbsDown.frame = CGRectMake(200, 20, 20, 15);
[thumbsDown setTag:indexpath.row+120];
[cell.contentView addSubview:thumbsDown];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[thumbsDown setBackgroundImage:[UIImage imageNamed:#"thumbsdown_not_selected.png"]
forState:UIControlStateNormal];
}
NSLog(#"------------> TAG TEST %d",thumbsUp.tag);
cell.text = [choices objectAtIndex:(indexpath.row % [choices count])];
NSLog(#"HELLO FOR TESTING");
return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
if (sectionTitle == nil) {
return nil;
}
// Create label with section title
UILabel *label = [[[UILabel alloc] init] autorelease];
label.frame = CGRectMake(15, 10, 300, 25);
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake(0.0, 1.0);
label.font = [UIFont boldSystemFontOfSize:16];
label.textAlignment = UITextAlignmentLeft;
label.text = sectionTitle;
// Create header view and add label as a subview
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(12, 0, 300, 60)];
[view autorelease];
[view addSubview:label];
//[view addSubview:segmentedControl];
view.backgroundColor = [UIColor grayColor];
return view;
}
//Thumbs Up Button Action
- (IBAction)thumbUp_ButtonClicked:(id)sender event:(id)event
{
NSLog(#"Thumbs Up Check!");
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *) [[button superview] superview];
NSIndexPath *indexPath = [myTable indexPathForCell:cell];
NSLog(#"indexpath =%d",indexPath.row);
//[button setTag:indexPath.row+(indexPath.section * 50)];
int cTag = [sender tag];
NSLog(#"------>TAG : %d", cTag);
NSLog(#"------> Calculated TAG %d",indexPath.row+(indexPath.section * 50));
if(cTag == (indexPath.row+(indexPath.section * 50)))
{
NSLog(#"BUTTON COUNT:");
[button setBackgroundImage:[UIImage imageNamed:#"thumbsup_selected.png"]
forState:UIControlStateNormal];
}
NSInteger section = indexPath.section;
NSInteger row = indexPath.row;
//int row = button.tag;
NSLog(#"SECTION IS:%d",section);
NSLog(#"ROW IS: %d",row);
NSArray *array = cell.contentView.subviews;
NSLog(#"NUMBER OF OBJECTS: %d",[array count]);
UIButton *test = (UIButton *)[array objectAtIndex:2];
[test setBackgroundImage:[UIImage imageNamed:#"thumbsdown_not_selected.png"]forState:UIControlStateNormal];
}
Due to issue with tag of button while I change image of one button several buttons are changing. If any one can please find a solution it will be helpful.... tag is setting for buttons in sections which we can view.

The reason is the bad use of the recycling/reuse mechanism (as with 75% of questions about UITableView…)
Go read the Table View Programming Guide in Apple's doc (and search SO and the web for any question related to tableview and the reuse mechanism)

Corrected the issue by creating buttons outside and inside if(cell == nil). Also created a mutable dictionary to keep the current state of the button.....

Related

accesing contents of uitableview cell in another class

i have a class loginViewController which has table contents. i have loaded a custom cell to each row of the table. in method cellForRowAtIndexPath i have created a button for each row and asigned it a tag value. clicking on this button takes us to new view controller logininsidesViewController. Now in logininsidesViewController class i want to access the button tag i created earlier.what should i do?
loginViewController.m class
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
customcell *cell=(customcell*)[tableView dequeueReusableCellWithIdentifier:#"cellcstm"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(customActionPressed)
forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:[UIImage imageNamed:#"add_black.png"] forState:UIControlStateNormal];
button.frame = CGRectMake(275 ,9, 25, 25);
[cell addSubview:button];
if (cell==nil)
{
//[tableView registerNib:[UINib nibWithNibName:#"customcell" bundle:nil] forCellReuseIdentifier:#"cellcstm"];
NSArray *arr12=[[NSBundle mainBundle]loadNibNamed:#"customcell" owner:self options:nil];
cell=[arr12 objectAtIndex:0];
}
for (int i=0; i<=indexPath.row; i++)
{
cell.selectionStyle=UITableViewCellEditingStyleNone;
}
if (indexPath.row==0)
{
cell.lbl.hidden=YES;
UILabel *l=[[UILabel alloc]init];
l.text=#"Login Templates";
l.frame=CGRectMake(100, 15, 180, 28);
[cell.contentView addSubview:l];
}
if (indexPath.row==1)
{
button.tag=1;
cell.img.image=[UIImage imageNamed:#"facebook.png"];
cell.lbl.text=#"Facebook";
[cell.contentView addSubview:button];
}
if (indexPath.row==2)
{
button.tag=2;
cell.img.image=[UIImage imageNamed:#"g+.png"];
cell.lbl.text=#"Google";
[cell.contentView addSubview:button];
}
if (indexPath.row==3)
{
button.tag=3;
cell.img.image=[UIImage imageNamed:#"youtube.png"];
cell.lbl.text=#"Youtube";
[cell.contentView addSubview:button];
}
if (indexPath.row==4)
{
button.tag=4;
cell.img.image=[UIImage imageNamed:#"twitter.png"];
cell.lbl.text=#"Twitter";
[cell.contentView addSubview:button];
}
if (indexPath.row==5)
{
button.tag=5;
cell.img.image=[UIImage imageNamed:#"flicker.png"];
cell.lbl.text=#"Flicker";
[cell.contentView addSubview:button];
}
else
{
cell .textLabel.text= [logarr objectAtIndex:indexPath.row];
}
return cell;
}
i want to access the button.tag in my logininsidesViewController class. plz help
In continuation with Viruss's answer you can create a property with integer type in logininsidesViewController class and pass that from button click.
-(IBAction) customActionPressed:(id)sender{
NSLog(#"button tag:%d",[sender tag]);
logininsidesViewController *objLoginInside = [[logininsidesViewController alloc] initWithNibName:#"logininsidesViewController" bundle:nil];
objLoginInside.buttonTag = sender.tag;
[self.navigationController pushViewController:objLoginInside animated:NO];
}
Add One target method to your buttons and access it with tags,
In cellForRow method Update to this.
[button addTarget:self action:#selector(customActionPressed:) forControlEvents:UIControlEventTouchUpInside];
You can access here with tag,
-(IBAction) customActionPressed:(id)sender{
NSLog(#"button tag:%d",[sender tag]);
}
You are adding your button on cell and again you're adding it on cell's contentView correct that is the problem.
If you want adding it in cell.contentView you must provide allocation in each if condition and then add it
Edit: Do smart coding
viewDidLoad()
[self.myTableView registerNib:[UINib nibWithNibName:#"CViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
arImage = #[#"facebook.png", #"g+.png", #"twitter.png", #"flicker.png" ];
arLables = #[#"Facebook", #"GooglePlus", #"Tweeter", #"Flicker"];
cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCell * cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(customActionPressed) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:[UIImage imageNamed:#"add_black.png"] forState:UIControlStateNormal];
button.frame = CGRectMake(275 ,9, 25, 25);
if (indexPath.row==0)
{
cell.lblText1.hidden=YES;
UILabel *l=[[UILabel alloc]init];
l.text=#"Login Templates";
l.frame=CGRectMake(100, 15, 180, 28);
[cell.contentView addSubview:l];
}
if ( indexPath.row > 0 && indexPath.row <= 5) {
button.tag = indexPath.row;
cell.imageView.image=[UIImage imageNamed:arImage[indexPath.row - 1]];
cell.textLabel.text=[arLables objectAtIndex:indexPath.row - 1];
[cell.contentView addSubview:button];
} else {
cell.textLabel.text= [logarr objectAtIndex:indexPath.row];
}
return cell;
}

Multiple Segment is Selected in SegmentController in iOS7

I have add one SegementController in CellForRowAtIndex method and its selected lasted value which we select previously. But once we move to other screen and come back to current then Segement will select the multiple option like this :
Here "Yes" is already selected and then i select "No",
Here is the code which i write in CellForRowAtIndexPath :
UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:#"Yes", #"No", #"Either", nil]];
seg.frame = CGRectMake(190.0f, 10.0f, 205.0f, 30.0f);
seg.selectedSegmentIndex = 0;
[seg setTintColor:[UIColor orangeColor]];
seg.segmentedControlStyle = UISegmentedControlStyleBar;
[seg addTarget:self action:#selector(segSelected:) forControlEvents:UIControlEventValueChanged];
seg.tag = indexPath.row;
cell.textLabel.frame = CGRectMake(10, 5, 150, 30);
[cell.contentView addSubview:seg];
seg.selectedSegmentIndex = [[[arryaSegment objectAtIndex:indexPath.row]objectForKey:#"SelecteKey"] intValue];
This is probably not about selecting 2 segments at the same time, but adding two segmentedControls at the same time because you add a new control each time the cell is displayed.
Make sure the code that adds the UISegmentedControl is only called once per cell.
e.g:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell; // = ... dequeue ...
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
// add segmented control only when creating a new cell
UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:#"Yes", #"No", #"Either", nil]];
seg.frame = CGRectMake(190.0f, 10.0f, 205.0f, 30.0f);
seg.selectedSegmentIndex = 0;
[seg setTintColor:[UIColor orangeColor]];
seg.segmentedControlStyle = UISegmentedControlStyleBar;
[seg addTarget:self action:#selector(segSelected:) forControlEvents:UIControlEventValueChanged];
cell.textLabel.frame = CGRectMake(10, 5, 150, 30);
[cell.contentView addSubview:seg];
seg.tag = 42; // used to reference segmentedControl in dequeued cell. see next line
}
UISegmentedControl *seg = (UISegmentedControl *)[cell.contentView viewWithTag:42];
seg.selectedSegmentIndex = [[[arryaSegment objectAtIndex:indexPath.row]objectForKey:#"SelecteKey"] intValue];
return cell;
}
since you can't use the ugly way of getting the indexPath with the tag of the segmentedControl anymore, you have to use a method which gets the indexPath in a different way. Something like this:
- (IBAction)segSelected:(UISegmentedControl *)sender {
CGPoint originOfSegmentedControlInTableView = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:originOfSegmentedControlInTableView];
...
}

how to show data to only visible tableview cells in ios

Hi guys i have a custom tableview cell with a scrollview in it.the problem is all the data is getting loaded in tableview cells at once.what i want is to load the data only for the visible cells in tableView.i used [indexPath forvisiblerows]; it was in vain..cud u guys help me out below is the code.
-(IPadTableViewCell *)getNewCell
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"IpadTableViewCell" owner:nil options:nil];
for (id currentObject in topLevelObjects)
{
if ([currentObject isKindOfClass:[IPadTableViewCell class]])
{
cell= (IPadTableViewCell *)currentObject;
return cell;
}
}
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// static NSString *CellIdentifier = #"IpadTableViewCell";
//cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
id1=[NSString stringWithFormat:#"%i",indexPath.row];
cell=[dicAlbumCells objectForKey:id1];
if (cell == nil) {
cell=[self getNewCell];
}
cell.tag=indexPath.row;
return cell;
}
-(void)loadImagesForOnscreenRows
{
NSArray *visiblePaths = [tblGallery indexPathsForVisibleRows];
for (NSIndexPath *indexPath in visiblePaths) {
if (imageArray > 0) {
[self imageButtonClicked:nil];
}
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[self loadImagesForOnscreenRows];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self loadImagesForOnscreenRows];
}
-(void)imageButtonClicked:(id)sender
{
CGFloat prevButtonXPosition = 18, pageButtonXPosition, pageButtonWidth = 144, pageButtonHeight = 143;
for (NSInteger i =0; i<9; i++) {
pageButtonXPosition = prevButtonXPosition ;
prevButtonXPosition = pageButtonXPosition+pageButtonWidth+20;
UIButton *pageButton = [UIButton buttonWithType:UIButtonTypeCustom];
[pageButton setContentMode:UIViewContentModeScaleAspectFit];
pageButton.layer.borderColor=[[UIColor whiteColor]CGColor];
pageButton.layer.borderWidth = 3;
pageButton.layer.cornerRadius = 0;
[pageButton addTarget:self action:#selector(onClickImage:) forControlEvents:UIControlEventTouchUpInside];
[pageButton setFrame:CGRectMake(pageButtonXPosition,0, pageButtonWidth, pageButtonHeight)];
[pageButton setBackgroundImage:[UIImage imageNamed:[imageArray objectAtIndex:i]] forState:UIControlStateNormal];
[pageButton setTag:i];
[cell.scrollView addSubview:pageButton];
}
UIButton *add=[UIButton buttonWithType:UIButtonTypeCustom];
add.layer.borderColor=[[UIColor whiteColor]CGColor];
add.layer.borderWidth = 3;
add.layer.cornerRadius = 0;
[add addTarget:self action:#selector(onClickAdd:) forControlEvents:UIControlEventTouchUpInside];
[add setFrame:CGRectMake(prevButtonXPosition, 0, 144, 143)];
[add setBackgroundImage:[UIImage imageNamed:#"grey.png"] forState:UIControlStateNormal];
[add setTag:0];
[cell.scrollView addSubview:add];
UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(prevButtonXPosition+35,30, 76,76)];
[iv setImage:[UIImage imageNamed:#"last.png"]];
[cell.scrollView addSubview:iv];
[cell.scrollView setContentSize:CGSizeMake(prevButtonXPosition +165, 40)];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell.contentView addSubview:cell.scrollView];
}

how to redirect to a new screen on the button click in the table view in objective c

I have created a table view and added some labels and displaying it, now i need a button in each cell, where on click on the button, it has redirect to the new screen.
The following is the code which i am trying to redirect,
- (void)viewDidLoad
{
vendorsArray = [CommonUserDetails sharedUserDetails].mVendorDictionary;
NSLog(#"vendorsArray is %# \n count is %d",vendorsArray,[vendorsArray count]);
loTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 43, 320, 400) style:UITableViewStylePlain];
[loTableView setBackgroundColor:[UIColor whiteColor]];
loTableView.delegate = self;
loTableView.dataSource = self;
loTableView.separatorColor = [UIColor grayColor];
[self.view addSubview:loTableView];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:#"myCell"];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifier:#"myCell"];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[self configureCell:cell forIndexPath:indexPath];
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#define L1_TAG 1
#define L2_TAG 2
#define L3_TAG 3
#define L4_TAG 4
- (UITableViewCell *)tableviewCellWithReuseIdentifier:(NSString *)identifier
{
UITableViewCell* cell = [[UITableViewCell alloc]initWithFrame:CGRectMake(0, 0, 320, 100)reuseIdentifier:identifier];
UILabel* l1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 290, 30)];
[l1 setBackgroundColor:[UIColor clearColor]];
[l1 setFont:[UIFont systemFontOfSize:14]];
// [l1 setTextColor:[UIColor blackColor]];
l1.textColor = [UIColor colorWithRed:153/(CGFloat)255 green:51/(CGFloat)255 blue:0 alpha:1.0];
[l1 setAdjustsFontSizeToFitWidth:YES];
[l1 setTextAlignment:UITextAlignmentRight];
l1.tag = L1_TAG;
[cell.contentView addSubview:l1];
UILabel* l2 = [[UILabel alloc] initWithFrame:CGRectMake(5, 20 , 300, 30)];
[l2 setBackgroundColor:[UIColor clearColor]];
l2.font = [UIFont boldSystemFontOfSize:14];
l2.textColor = [UIColor blackColor];
//l2.textColor = [UIColor colorWithRed:102/(CGFloat)255 green:102/(CGFloat)255 blue:153/(CGFloat)255 alpha:1.0];
l2.tag = L2_TAG;
[l2 setTextAlignment:UITextAlignmentLeft];
[cell.contentView addSubview:l2];
UILabel* l3 = [[UILabel alloc] initWithFrame:CGRectMake(5, 40, 190, 30)];
[l3 setBackgroundColor:[UIColor clearColor]];
[l3 setFont:[UIFont systemFontOfSize:14]];
[l3 setTextColor:[UIColor grayColor]];
// l3.textColor = [UIColor colorWithRed:102/(CGFloat)255 green:102/(CGFloat)255 blue:0/(CGFloat)255 alpha:1.0];
[l3 setAdjustsFontSizeToFitWidth:YES];
l3.tag = L3_TAG;
[cell.contentView addSubview:l3];
UILabel* l4 = [[UILabel alloc] initWithFrame:CGRectMake(5, 60, 190, 30)];
[l4 setBackgroundColor:[UIColor clearColor]];
[l4 setFont:[UIFont systemFontOfSize:14]];
[l4 setTextColor:[UIColor grayColor]];
//l4.textColor = [UIColor colorWithRed:0/(CGFloat)255 green:51/(CGFloat)255 blue:0/(CGFloat)255 alpha:1.0];
[l4 setAdjustsFontSizeToFitWidth:YES];
l4.tag = L4_TAG;
[cell.contentView addSubview:l4];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(150, 60, 70, 30);
[button setTitle:#"Pay" forState:UIControlStateNormal];
[cell.contentView addSubview:button];
[button addTarget:self action:#selector(payButton)
forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
UILabel *myl1 = (UILabel*)[cell viewWithTag:L1_TAG];
UILabel *myl2 = (UILabel*)[cell viewWithTag:L2_TAG];
UILabel *myl3 = (UILabel*)[cell viewWithTag:L3_TAG];
UILabel *myl4 = (UILabel*)[cell viewWithTag:L4_TAG];
NSDictionary *dictionary = [vendorsArray objectAtIndex:indexPath.row];
myl1.text= [NSString stringWithFormat:#"INo:%#",[dictionary objectForKey:#"iNo"]];
myl2.text=[dictionary objectForKey:#"vendorName"];
myl3.text= [NSString stringWithFormat:#"Amount:%#",[dictionary objectForKey:#"amount"]];
myl4.text= [NSString stringWithFormat:#"DDate:%#",[dictionary objectForKey:#"dDate"]];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
NSLog(#"count is %d",[vendorsArray count]);
return [vendorsArray count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return #"Payables";
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100;
}
-(IBAction) payButton{
PayDescriptionController *mPayDescriptionController = [[PayDescriptionController alloc]initWithNibName:#"PayDescriptionController" bundle:nil];
mPayDescriptionController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self.navigationController presentModalViewController:mPayDescriptionController animated:YES];
}
Where i am going wrong in the above code.
try this,
[self.navigationController pushViewController:mPayDescriptionController animated:YES];
see ,it is navigating to next view or not !! and if not then may be one of your object is null.

UITableViewCell - overlapping with previous cells contents

I have this wierd problem with my table
i Have about 20 cells to display
Each cell is about 84px in height
When i click no the cell, i have set a background colour
The first 4 cells are ok, but when i scroll down and click on the 5th cell, the content of each cell starts to overlap with some other content, usually content from 1st 4 cells.
I belive its some cell reusability or drawing issue. Am not sure how to solve it, i have checked through my code, but i am not changing the cell's content on touch.
Here is my code and will add some pics too
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 104;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [stores count];
}
-(UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CGRect Label1Frame = CGRectMake(5, 5, 250, 30);
CGRect Label2Frame = CGRectMake(6, 42, 220, 20);
CGRect Label3Frame = CGRectMake(6, 62, 220, 20);
CGRect Label4Frame = CGRectMake(240,56, 70, 12);
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}else{
// a cell is being recycled, remove the old edit field (if it contains one of our tagged edit fields)
UIView *viewToCheck = nil;
viewToCheck = [cell.contentView viewWithTag:1];
if (!viewToCheck) {
[viewToCheck removeFromSuperview];
DebugLog(#"View removed");
}
}
//cell.selectionStyle=UITableViewCellSelectionStyleNone;
[cell setSelectedBackgroundView:bgView];
NSInteger row=indexPath.row;
UILabel *lblTemp;
[[cell contentView] clearsContextBeforeDrawing];
//Line 1
lblTemp=[[UILabel alloc] initWithFrame: Label1Frame];
lblTemp.tag=1;
lblTemp.text=[[stores objectAtIndex:row] objectAtIndex:0] ;
lblTemp.numberOfLines=2;
lblTemp.font = [UIFont boldSystemFontOfSize:13];
lblTemp.adjustsFontSizeToFitWidth=YES;
lblTemp.minimumFontSize=12;
lblTemp.textColor = [UIColor grayColor];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
//Line 2
lblTemp = [[UILabel alloc] initWithFrame:Label2Frame];
lblTemp.tag = 2;
lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:1];
lblTemp.font = [UIFont systemFontOfSize:12];
lblTemp.textColor = [UIColor grayColor ];
lblTemp.textAlignment=UITextAlignmentLeft;
lblTemp.adjustsFontSizeToFitWidth=YES;
lblTemp.minimumFontSize=12;
[cell.contentView addSubview:lblTemp];
[lblTemp release];
//Line 3
lblTemp = [[UILabel alloc] initWithFrame:Label3Frame];
lblTemp.tag = 3;
lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:2];
lblTemp.font = [UIFont systemFontOfSize:12];
lblTemp.textColor = [UIColor grayColor ];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
//Phone button
UIButton *phoneButton=[[UIButton alloc] initWithFrame:CGRectMake(240,16,30,30)];
[phoneButton setBackgroundImage:[UIImage imageNamed:#"phone.png"] forState:UIControlStateNormal];
[phoneButton setTag:row];
[phoneButton addTarget:self action:#selector(dialNumber:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:phoneButton];
//ANnotation button
UIButton *annotation=[[UIButton alloc] initWithFrame:CGRectMake(274,16,30,30)];
[annotation setTag:row];
[annotation setBackgroundImage:[UIImage imageNamed:#"tab.png"] forState:UIControlStateNormal];
[annotation addTarget:self action:#selector(openMap:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:annotation];
[annotation release];
//Distance label
//Line 3
lblTemp = [[UILabel alloc] initWithFrame:Label4Frame];
lblTemp.tag = 4;
lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:5];
lblTemp.textAlignment=UITextAlignmentCenter;
lblTemp.font = [UIFont systemFontOfSize:13];
lblTemp.textColor = [UIColor grayColor ];
[lblTemp setAdjustsFontSizeToFitWidth:YES];
[cell.contentView addSubview:lblTemp];
[phoneButton release];
[lblTemp release];
[cell setNeedsLayout];
[cell setNeedsDisplay];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath ];
for(UILabel *lbl in cell.contentView.subviews){
if([lbl isKindOfClass:[UILabel class]]){
lbl.textColor=[UIColor whiteColor];
}
}
//UITableViewCell *cell1;
//NSString *row=[NSString stringWithFormat:#"%d",indexPath.row];
svm = [[storesMapView alloc] initWithNibName:#"storesMapView" bundle:nil];
[svm initWithXML:stores:indexPath.row];
CGRect theFrame = svm.view.frame;
theFrame.origin = CGPointMake(self.view.frame.size.width, 0);
svm.view.frame = theFrame;
theFrame.origin = CGPointMake(0,0);
theFrame.size=CGSizeMake(320,355);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3f];
svm.view.frame = theFrame;
[UIView commitAnimations];
[subView addSubview:svm.view];
backButton.hidden=NO;
}
I figured it out with some trial and error; if this can help some one
In cellforRowAtIndexPath i tried to clear all the cells subview before drawing the cell
//TRY TO REMOVE ALL CONTENT
for(UIView *view in cell.contentView.subviews){
if ([view isKindOfClass:[UIView class]]) {
[view removeFromSuperview];
}
}
I would be happy if someone can point me to some easier way
Thanks
You can use
[[[cell contentView] subviews] makeObjectsPerformSelector: #selector(removeFromSuperview)];
If the cell in not nil, the above code will reduce the time for using the for loop similar to this
for(UIView *eachView in [cell subviews])
[eachView removeFromSuperview];
I also had the same issue.I also had composed tableView with labels.And when I scroll it down the contents got overlapped.But it got solved simply by editing one statement in cellForRowAtIndexPath.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
I think this will solve your problem.
I know this is a bit late, but I had a similar issue where UILabels created for a cell were still part of the cell when it was reused. So each successive update of the tableview created another UILabel on top of the existing one. I moved the creation of the Labels into the if condition as below and it resolved my issue. Hope it helps someone else. Also note no release as I am using ARC.
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cityText = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
cityText.font = [UIFont fontWithName:#"Arial" size:20];
cityText.textAlignment = UITextAlignmentLeft;
cityText.backgroundColor = [UIColor clearColor];
regionText = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 100, 20)];
regionText.font = [UIFont fontWithName:#"Arial" size:20];
regionText.textAlignment = UITextAlignmentLeft;
regionText.backgroundColor = [UIColor clearColor];
}
Setting nil to label text on UITableViewCell subclass 's method prepareForReuse() solved my problem -
override func prepareForReuse() {
super.prepareForReuse()
self.label1.text = nil
self.label2.text = nil
....
}
Shared if it helps anyone!