Expand and collapse the tableview row - ios

I am developing an iOS application. I have one expandable and collapsed tableview. On click the cell of tableview, the tableview cell expands properly but when I click on a second cell I want first cell to collapse and the second to expand. This would leave only one cell expanded at a time.
I am using class HVTableview:-
Code:-
-(void)tableView:(UITableView *)tableView expandCell: (UITableViewCell*)cell withIndexPath:(NSIndexPath*) indexPath;
{
UILabel *detail = (UILabel *)[cell viewWithTag:3];
UIButton *button = (UIButton *)[cell viewWithTag:10];
button.alpha = 0;
button.hidden = NO;
[UIView animateWithDuration:.5 animations:^{
detail.text = #"This is Expand.";
button.alpha = 1;
[cell.contentView viewWithTag:7].transform = CGAffineTransformMakeRotation(3.14);
}];
}
-(void)tableView:(UITableView *)tableView collapseCell: (UITableViewCell*)cell withIndexPath:(NSIndexPath*) indexPath;
{
UILabel *detail = (UILabel *)[cell viewWithTag:3];
UIButton *button = (UIButton *)[cell viewWithTag:10];
button.alpha = 0;
[UIView animateWithDuration:.5 animations:^{
detail.text = #"This is Collapse.";
button.alpha = 0;
[cell.contentView viewWithTag:7].transform = CGAffineTransformMakeRotation(-3.14);
} completion:^(BOOL finished) {
button.hidden = YES;
}];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_cites count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath isExpanded: (BOOL)isExpanded;
{
if (isExpanded) {
return 150;
}else
{
return 100;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath isExpanded:(BOOL)isExpanded;
{
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UILabel *title = (UILabel *)[cell viewWithTag:2];
UILabel *detail = (UILabel *)[cell viewWithTag:3];
UIImageView *image = (UIImageView *)[cell viewWithTag:1];
UIButton *button = (UIButton *)[cell viewWithTag:10];
[button addTarget:self action:#selector(goToTop) forControlEvents:UIControlEventTouchUpInside];
title.text = [_cites objectAtIndex:indexPath.row % 9];
NSString* bundlePath = [[NSBundle mainBundle] bundlePath];
NSString* imageFileName = [NSString stringWithFormat:#"%d.jpg", indexPath.row % 9 + 1];
image.image = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:#"%#/%#", bundlePath, imageFileName]];
if (indexPath.row %2 ==1)
cell.backgroundColor = [UIColor colorWithRed:.9 green:.9 blue:.9 alpha:1];
else
cell.backgroundColor = [UIColor colorWithRed:.8 green:.8 blue:.8 alpha:1];
if (!isExpanded)
{
detail.text = #"This is collapse";
[cell.contentView viewWithTag:7].transform = CGAffineTransformMakeRotation(0);
button.hidden = YES;
}
else
{
detail.text = #"This is Expand";
[cell.contentView viewWithTag:7].transform = CGAffineTransformMakeRotation(3.14);
button.hidden = NO;
}
return cell;
}

- (void) collapseExpandButtonTap:(id) sender
{
UIButton* aButton = (UIButton*)sender; //It's actually a button
NSIndexPath* aPath = [self indexPathForCellWithButtonTag:aButton.tag]; //Let's assume that you have only one section and button tags directly correspond to rows of your cells.
//expandedCells is a mutable set declared in your interface section or private class extensiont
if ([expandedCells containsObject:aPath])
{
[expandedCells removeObject:aPath];
}
else
{
[expandedCells addObject:aPath];
}
[myTableView beginEditing];
[myTableView endEditing]; //Yeah, that old trick to animate cell expand/collapse
}
In UITableViewDelegate method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([expandedCells containsObject:indexPath])
{
return kExpandedCellHeight; //It's not necessary a constant, though
}
else
{
return kNormalCellHeigh; //Again not necessary a constant
}
}
Key thing here is to determine if your cell should be expanded/collapsed and return right height in delegate method. So accordingly design your requirements.

Related

Tableview scrolling Checked button image automatically hide

I am developing IOS App. Using tableview to expand and collpase. Add Button on TableviewCell for check or Uncheck. Example I am Selected First Row button. Than scrolling tableview and select last header to last row button selected. Than again scrolling and see first index selected button image hidden.
Code..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (self.sectionNames.count > 0) {
_tableView.backgroundView = nil;
return self.sectionNames.count;
}
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSMutableArray *arrayOfItems = [self.sectionItems objectAtIndex:section];
return arrayOfItems.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (self.sectionNames.count) {
return [self.sectionNames objectAtIndex:section];
}
return #"";
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section; {
return 44.0;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
// recast your view as a UITableViewHeaderFooterView
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
// header.contentView.backgroundColor = [UIColor colorWithHexString:#"#484848"];
header.contentView.backgroundColor = [UIColor lightGrayColor];
header.textLabel.textColor = [UIColor whiteColor];
header.textLabel.font = [UIFont fontWithName:#"SourceSansPro SemiBold" size:15.0];
UIImageView *viewWithTag = [self.view viewWithTag:kHeaderSectionTag + section];
if (viewWithTag) {
[viewWithTag removeFromSuperview];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = nil;
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// for(UIView *subview in [cell subviews]) {
// [subview removeFromSuperview];
// }
UILabel *sectionLabel = [[UILabel alloc]initWithFrame:CGRectMake(35.0f, 12.0f, 120.0f, 20.f)];
sectionLabel.font = [UIFont systemFontOfSize:14.0f];
sectionLabel.textColor = [UIColor blackColor];
sectionLabel.lineBreakMode = NSLineBreakByWordWrapping;
sectionLabel.numberOfLines = 3;
[cell addSubview:sectionLabel];
NSArray *section = [self.sectionItems objectAtIndex:indexPath.section];
sectionLabel.text = [section objectAtIndex:indexPath.row];
UIButton *button = [[UIButton alloc]initWithFrame: CGRectMake(5.0f, 9.0f, 25.0f, 25.0f)];
button.layer.borderColor=[[UIColor colorWithRed:244.0f/255.0f
green:129.0f/255.0f
blue:32.0f/255.0f
alpha:1.0] CGColor];
[button.layer setBorderWidth: 1.0];
button.tag = indexPath.section;
NSString *data = [section objectAtIndex:indexPath.row]; //For Selected Fliters
for (int i=0; i<[filterArray count]; i++) {
NSDictionary *dict = [filterArray objectAtIndex:i];
NSString *fliterTickValue = [dict valueForKey:#"filterValue"];
if ([fliterTickValue isEqualToString:data]) {
UIImage *img = [UIImage imageNamed:#"tick.png"];
[button setImage: img forState:UIControlStateNormal];
}else{
UIImage *img = [UIImage imageNamed:#""];
[button setImage: img forState:UIControlStateNormal];
}
}
[button addTarget:self action:#selector(fliterFields:) forControlEvents:UIControlEventTouchDown];
[cell addSubview:button];
return cell;
}
Imho, your calls [cell addSubview:] is not correct. In case that cell is re-used, it will already have those subviews and resulting layout of your cell is not quite clear.
I suggest you to design your cell in xib and load it when needed. Then your cellForRowAtIndexPath becomes simpler and deals mostly with data populating. Subviews you don't need at the moment can be hidden and so on. If you need code and design example - let me know.

How to change button background color which is added on table view cell when we tapped on it?

I have added one custom button on tableview cell and everything is ok.
But here my main requirement is when I click that button for the "first time" which is added on table view cell, then the button background color needs to change(to red) and when I click the second time the button, the previous color needs to be displayed(back to white)
My code:
#import "ViewController2.h"
#interface ViewController2 ()
{
NSArray * Mainarray;
UITableView * MaintableView;
UIImageView * accessoryView;
UIButton *button;
BOOL tapped;
}
#end
#implementation ViewController2
- (void)viewDidLoad
{
[super viewDidLoad];
tapped = NO;
Mainarray = [[NSArray alloc]initWithObjects:#"Ram",#"Rama",#"Rakesh",#"Ranjith", nil];
self.view.backgroundColor = [UIColor darkGrayColor];
MaintableView = [[UITableView alloc]init];
MaintableView.translatesAutoresizingMaskIntoConstraints = NO;
MaintableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
MaintableView.dataSource=self;
MaintableView.delegate=self;
MaintableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[MaintableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
[self.view addSubview:MaintableView];
NSDictionary * views = NSDictionaryOfVariableBindings(MaintableView);
NSArray * horizentalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[MaintableView]-0-|" options:0 metrics:nil views:views];
NSArray * verticalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[MaintableView]-0-|"options:0 metrics:nil views:views];
[self.view addConstraints:horizentalConstraint];
[self.view addConstraints:verticalConstraint];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return Mainarray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 50;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *Cell = [MaintableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (Cell == nil)
{
Cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.textLabel.text = [Mainarray objectAtIndex:indexPath.row];
button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=indexPath.row;
[button addTarget:self
action:#selector(aMethod:) forControlEvents:UIControlEventTouchDown];
[button setTitle:#"" forState:UIControlStateNormal];
button.frame = CGRectMake(Cell.frame.size.width - 50, 10, 30, 30);
button.layer.cornerRadius = 60/2.0f;
button.layer.borderColor=[UIColor blackColor].CGColor;
button.backgroundColor = [UIColor whiteColor];
button.layer.borderWidth=2.0f;
//setting tag to button
button.tag=indexPath.row;
[Cell.contentView addSubview:button];
return Cell;
}
-(void)aMethod :(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:MaintableView];
NSIndexPath *indexPath1 = [MaintableView indexPathForRowAtPoint:buttonPosition];
NSInteger variable = indexPath1.row;
NSLog(#"ok it is %ld",(long)variable);
if(button.tag == variable){
button.backgroundColor= tapped ? [UIColor whiteColor]:[UIColor redColor];
tapped = YES;
}
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell respondsToSelector:#selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:#selector(setPreservesSuperviewLayoutMargins:)]) {
[cell setPreservesSuperviewLayoutMargins:NO];
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
#end
You can create an array in which u can store selected buttons.
Example:
var selectedButtons: [Bool] = [Bool](count: N, repeatedValue: false)
In your cellForRowAtIndexPath:
if selectedButtons[indexPath.row] {
yourButton.backgroundColor = UIColor.redColor()
} else {
yourButton.backgroundColor = UIColor.whiteColor()
}
Then in your tableView didSelectRowAtIndexPath you can say:
selectedButtons[indexPath.row] = true
tableView.reloadData()
Sorry, my code is in Swift but it isn't hard to convert it to Obj-C.
Give your button a tag value in the cellForRowIndexpath method:
button.tag=indexPath.row;
and in your view did load, make the BOOL as a property in your .m file and make it accessible for the whole class
BOOL tapped =NO;
and then in your button action method:
-(IBAction)buttonMethod:(id)sender{
if(sender.tag==0){
button.backgroundColor= tapped ? [UIColor whiteColor]:[UIColor redColor];
tapped = !tapped;
}
}
Please try below code. Hope this is work for you.
-(void)aMethod:(id)sender
{
UIButton *btn = (UIButton *)sender;
if ([btn.backgroundColor isEqual:[UIColor redColor]]) {
btn.backgroundColor = [UIColor whiteColor];
}
else{
btn.backgroundColor = [UIColor redColor];
}
}
Thanks.. :)
I tried to get the solution for your question and finally i got.
First you have to change Button Type RECT to CUSTOM in Attributes Inspector.Because in button type RECT the default background color of button is BLUE.So when you click for changing the color of the button, it comes actual color(it changes to your required color) with BLUE color.So you need to set the button type as CUSTOM.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrayButtonData.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
customCell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"cell"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
if (customCell==nil)
{
customCell = [nib objectAtIndex:0];
}
customCell.labelArrayListsNames.text = [NSString stringWithFormat:#"%#",[arrayButtonData objectAtIndex:indexPath.row]];
customCell.imageCircleRound.tag = indexPath.row;
NSLog(#"The custom cell button tag is - %ld",(long)customCell.imageCircleRound.tag);
NSLog(#"The label text is - %#",customCell.labelArrayListsNames.text);
[customCell.imageCircleRound addTarget:self action:#selector(cellCustomButtonClicked:)
forControlEvents:UIControlEventTouchUpInside];;
return customCell;
}
-(void)cellCustomButtonClicked:(UIButton *)sender
{
if(![sender isSelected])
{
[sender setBackgroundColor:[UIColor redColor]];
sender.Selected = YES;
}
else
{
[sender setBackgroundColor:[UIColor whiteColor]];
sender.Selected = NO;
}
}
It works fine.Check it.
enter code hereFor such problem use array of dictionary for tableview datasource array. Like this
NSMutableDictionary *datadict = [[NSMutableDictionary alloc] init];
[datadict setObject:#"Your title" forKey:#"Title"];
[datadict setObject:#"N" forKey:#"isSelected"];
[mainArray addObject: datadict]
put this code in loop for all your titles and N for isSelected key first time.
then you tableview method specially cellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *Cell = [MaintableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (Cell == nil)
{
Cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.textLabel.text = [[mainArray objectAtIndex:indexPath.row] objectForKey:#"Title"];
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=indexPath.row;
[button addTarget:self
action:#selector(aMethod:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"" forState:UIControlStateNormal];
button.frame = CGRectMake(Cell.frame.size.width - 50, 10, 30, 30);
button.layer.cornerRadius = 60/2.0f;
button.layer.borderColor=[UIColor blackColor].CGColor;
if([[[mainArray objectAtIndex:indexPath.row] objectForKey:#"isSelected"] isEqualToString:#"Y"])
{
button.backgroundColor = [UIColor redColor];
}
else
{
button.backgroundColor = [UIColor whiteColor];
}
button.layer.borderWidth=2.0f;
//setting tag to button
button.tag=indexPath.row;
[Cell.contentView addSubview:button];
return Cell;
}
Then in your button action should be like
-(IBAction)aMethod :(id)sender
{
UIButton *selectedBtn = (UIButton *)sender;
if([[[mainArray objectAtIndex:[sender tag]] objectForKey:#"isSelected"] isEqualToString:#"Y"])
{
selectedBtn.backgroundColor = [UIColor whiteColor];
[[mainArray objectAtIndex:[sender tag]] removeObjectForKey:#"isSelected"];
[[mainArray objectAtIndex:[sender tag]] setObject:#"N" forKey:#"isSelected"];
}
else
{
selectedBtn.backgroundColor = [UIColor redColor];
[[mainArray objectAtIndex:[sender tag]] removeObjectForKey:#"isSelected"];
[[mainArray objectAtIndex:[sender tag]] setObject:#"Y" forKey:#"isSelected"];
}
}
you can also reload table in button action to see effect. It is good code technique to maintain multiple row selection and where data is large and realtime. By this we can get all selected rows whenever we needed on any event.

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;
}

Uncheck row automatically when table scrolled

When I scroll UITableView my tableview cells automatically uncheck. But when I press done button it give me selected rows I can't understand why is this happening.
My Tableview code is as below :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
idArray = [[NSMutableArray alloc]init];
NSLog(#"Cat Array : %#",catArray);
isSelectAllBtnClicked = NO;
serviceArray = [[NSArray alloc]initWithObjects:#"Anal", #"Cuffed", #"Foreplay", #"Masturbation", #"Scat", #"Blindfolded",#"Deep throat", #"French Kissing", #"Missionary", #"Shower for 2", #"Bottom", #"Dinner Date", #"Full Bondage", #"Mutual Masturbation", #"Spanking", #"Boy on Boy", #"Dirty Talk",#"Girl on Girl", #"On top", #"Strap on", #"Choking", #"Doggy", #"Girlfriend Experience", #"Oral", #"Striptease", #"CIM", #"Dominate", #"Golden Shower",#"Oral Mutual", #"Submissive", #"COB", #"Fantasy", #"Kissing", #"Overnight", #"Top", #"COF", #"Fetish", #"Light Bondage", #"Rim me",#"Touching", #"Couples", #"Fisting", #"Lingerie", #"Rim you", #"Toys for me", #"Cuddling", #"Foot fetish", #"Massage", #"Role Play", #"Toys for you", nil];
[myTableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseIdentifier = #"reuseIdentifier";
UITableViewCell *cell = [[UITableViewCell alloc]init];
if (cell != NULL)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
}
cell.selectionStyle = UITableViewCellEditingStyleNone;
cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"list_row_bg.png"]] autorelease];
UILabel *catListLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 310, 20)];
NSString *strValue = [[NSUserDefaults standardUserDefaults]valueForKey:#"service"];
if ([strValue isEqualToString:#"service"])
{
catListLbl.text = [serviceArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Services";
}
else
{
catListLbl.text = [catArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Category";
}
catListLbl.textColor = [UIColor colorWithRed:244/255.0 green:29/255.0 blue:94/255.0 alpha:1.0];
catListLbl.backgroundColor = [UIColor clearColor];
[cell addSubview:catListLbl];
if (isSelectAllBtnClicked) {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox_check.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
[myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
[self tableView:myTableView didSelectRowAtIndexPath:indexPath];
}
else {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int buttonTag = indexPath.row + 200;
//NSLog(#"%i",buttonTag);
UIButton *tempBtn = (UIButton *)[self.view viewWithTag:buttonTag];
[tempBtn setBackgroundImage:[UIImage imageNamed:#"checkbox_check.png"]forState:UIControlStateNormal];
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
int buttonTag = indexPath.row + 200;
NSLog(#"%i",buttonTag);
UIButton *tempBtn = (UIButton *)[self.view viewWithTag:buttonTag];
[tempBtn setBackgroundImage:[UIImage imageNamed:#"checkbox.png"]forState:UIControlStateNormal];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int count;
NSString *strValue = [[NSUserDefaults standardUserDefaults]valueForKey:#"service"];
if ([strValue isEqualToString:#"service"])
{
count = [serviceArray count];
}
else
{
count = [catArray count];
}
return count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
thanks in advance.
when ever you scroll the table
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
method executes and you have not mentioned any condition by which it can be judged that this row was previously selected or not. you have to insert a condition along with indexPath.row and check whether it is prviously selected or not
try like this ,when you scroll the tableview every time isSelectAllBtnClicked value is 0 that's why every time button changed.
when you scroll the table every time new cell created try to avoid that one
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"%d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell.selectionStyle = UITableViewCellEditingStyleNone;
cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"list_row_bg.png"]] autorelease];
UILabel *catListLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 310, 20)];
NSString *strValue = [[NSUserDefaults standardUserDefaults]valueForKey:#"service"];
if ([strValue isEqualToString:#"service"])
{
catListLbl.text = [serviceArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Services";
}
else
{
catListLbl.text = [catArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Category";
}
catListLbl.textColor = [UIColor colorWithRed:244/255.0 green:29/255.0 blue:94/255.0 alpha:1.0];
catListLbl.backgroundColor = [UIColor clearColor];
[cell addSubview:catListLbl];
if (isSelectAllBtnClicked) {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox_check.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
[myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
[self tableView:myTableView didSelectRowAtIndexPath:indexPath];
}
else {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
}
}
}

titleForHeaderSection from NSTableViewCell

How can I retrieve the current header section name from an NSTableViewCell item?
Currently I have a method called configureCell which determines how to style the custom cell I have. This data comes from a pList file.
-(void)configureCell:(UITableViewCell *)tableViewCell forIndexPath:(NSIndexPath *)indexPath{
UILabel *label;
UIView *backView;
// NSString *country = [self tableView: tableViewCell titleForHeaderInSection:indexPath.section];
NSString *fatPercent = [[self.milkTypes valueForKey:#"Finland"] objectAtIndex:indexPath.row];
label = (UILabel *)[tableViewCell viewWithTag:1];
label.text = #"Fat Percent test";
backView = (UIView *)[tableViewCell viewWithTag:2];
backView.backgroundColor = [self colorWithHexString: fatPercent];
}
Where I've commented out the line for *country I need to retrieve the current section I'm in. Currently it's statically set to Finland which is the array name from the pList.
For a better understanding on how my code is laid out, here is the majority of the Table Controller.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.milkTypes count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[self.milkTypes allKeys] objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *country = [self tableView:tableView titleForHeaderInSection:section];
return [[self.milkTypes valueForKey:country] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier;
UITableViewCell *cell;
cellIdentifier = [NSString stringWithFormat:#"MilkCell"];
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==nil) {
cell = [self tableViewCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
}
[self configureCell:cell forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
-(UITableViewCell *)tableViewCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath{
CGRect rect;
UILabel *label;
UIView *backView;
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
float center = (float) (40-20)/2;
rect = CGRectMake(15, center, 270, 20);
label = [[UILabel alloc] initWithFrame:rect];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
label.tag = 1;
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
[cell.contentView addSubview:label];
[label release];
rect = CGRectMake(280, 10, 20, 40-20);
backView = [[UIView alloc] initWithFrame:rect];
backView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth;
backView.backgroundColor = [UIColor clearColor];
backView.tag = 2;
[cell.contentView addSubview:backView];
[backView release];
return cell;
}
-(void)configureCell:(UITableViewCell *)tableViewCell forIndexPath:(NSIndexPath *)indexPath {
UILabel *label;
UIView *backView;
// NSString *country = [self tableView: tableViewCell titleForHeaderInSection:indexPath.section];
NSString *fatPercent = [[self.milkTypes valueForKey:#"Sweden"] objectAtIndex:indexPath.row];
label = (UILabel *)[tableViewCell viewWithTag:1];
label.text = #"Fat Percent test";
backView = (UIView *)[tableViewCell viewWithTag:2];
backView.backgroundColor = [self colorWithHexString: fatPercent];
}
It seems you already have it anyway, in [[self.milkTypes allKeys] objectAtIndex:section] - just use that instead, so
NSString *country = [[self.milkTypes allKeys] objectAtIndex: indexPath.section];

Resources