Tableview scrolling Checked button image automatically hide - ios

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.

Related

Expand and collapse the tableview row

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.

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.

How can i change background color of UIButton on click in UITableviewCell?

I have UITableviewCell and i placed 4 buttons in cell. When i click one button i need to change its background color to red.
Soo right now i have written code for this and when i click one button then that button background color is not changing instead of that same button in some other row changing background color.
Use case:
1.I have 10 rows in UITableView and each cell contains 4 buttons named as
"Good","Better","Best","Worst".
When i click on "Good" button in first row am expecting it should change color to red.
3.Right now if i click "Good " button in first row then its not changing color instead while scrolling down but i can see "Good" button in 4th and 8th is changed to red .
So some mistake in my code for changing color.
Please check my tableview code and Button click code
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int sectionCount;
if(section==0)
{
sectionCount=4;
}else if(section==1){
sectionCount=4;
}else if (section==2){
sectionCount=3;
}else if(section==3){
sectionCount=1;
}
return sectionCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
sharedManager=[Mymanager sharedManager];
static NSString *CellIdentifier = #"cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[questioncell alloc] initWithStyle:UITableViewCellStyleValue1
reuseIdentifier:CellIdentifier];
}
cell.excellentButton.tag=indexPath.row;
cell.goodButotn.tag=indexPath.row;
cell.fineButton.tag=indexPath.row;
cell.dorrButton.tag=indexPath.row;
if(indexPath.section==0){
cell.question.text=[questions objectAtIndex:indexPath.row];
} else if(indexPath.section==1){
cell.question.text=[section1 objectAtIndex:indexPath.row];
}else if(indexPath.section==2){
cell.question.text=[section2 objectAtIndex:indexPath.row];
}else if(indexPath.section==3){
cell.question.text=[section3 objectAtIndex:indexPath.row];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 200;
}
Button click code
- (IBAction)goodButton:(id)sender {
UIButton *button = (UIButton *)sender; // first, cast the sender to UIButton
NSInteger row = button.tag; // recover the row
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
NSString *key=[NSString stringWithFormat:#"%ld",(long)indexPath.row];
[sharedManager.ratingDic setValue:#"Good" forKey:key];
cell.goodButotn.layer.backgroundColor=[[UIColor colorWithRed:39/255.0 green:174/255.0 blue:96/255.0 alpha:100] CGColor ];
cell.betterButton.layer.backgroundColor=[[UIColor clearColor] CGColor ];
cell.bestButton.layer.backgroundColor=[[UIColor clearColor] CGColor ];
cell.worstButton.layer.backgroundColor=[[UIColor clearColor] CGColor ];
}
Please help me to clear this issue
UIButton *button = (UIButton *)sender; <-- this is already your reference to the button. I see there 2 ways to do it
create a custom UITableViewCell and implement methods for resetting all colors and setting the correct color. This is the clean way. Here you can implement more logic and have always the correct corresponding data. Here every of your buttons call an own method and there you have also a clear method.
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if( self = [super initWithStyle:style reuseIdentifier:reuseIdentifier] )
{
[excellentButton addTarget:self action:#selector(clickedExcellentButton) forControlEvents:UIControlEventTouchDown]; // or TouchUp, how ever you like
[goodButton addTarget:self action:#selector(clickedGoodButton) forControlEvents:UIControlEventTouchDown];
[fineButton addTarget:self action:#selector(clickedFineButton) forControlEvents:UIControlEventTouchDown];
[dorrButton addTarget:self action:#selector(clickedWoButton) forControlEvents:UIControlEventTouchDown];
}
return self;
}
-(UIColor *)selectionColor
{
return [UIColor colorWithRed:39/255.0 green:174/255.0 blue:96/255.0 alpha:100];
}
-(void)resetSelection
{
excellentButton.backgroundColor = [UIColor clearColor];
goodButton.backgroundColor = [UIColor clearColor];
fineButton.backgroundColor = [UIColor clearColor];
dorrButton.backgroundColor = [UIColor clearColor];
}
-(void)clickedExcellentButton
{
[self resetSelection];
excellentButton.backgroundColor = [self selectionColor];
NSString *key=[NSString stringWithFormat:#"%ld",(long)indexPath.row];
[sharedManager.ratingDic setValue:#"Excellent" forKey:key]; // if you have your sharedManager object here. If you cannot access it from here, you have to forward it or give the cell a reference to it
}
-(void)clickedGoodButton
{
[self resetSelection];
goodButton.backgroundColor = [self selectionColor];
NSString *key=[NSString stringWithFormat:#"%ld",(long)indexPath.row];
[sharedManager.ratingDic setValue:#"Good" forKey:key];
}
...
or
- (IBAction)goodButton:(id)sender {
UIButton *button = (UIButton *)sender; // this is the button that was clicked
// [...]
for(UIButton *ctrl in [button.superview subviews]) // button.superview get the view that holds him. Subviews all the others in his layer
{
if([ctrl isKindOfClass:[UIButton class]])
{
ctrl.backgroundColor = [UIColor clearColor];
}
}
button.backgroundColor = [UIColor colorWithRed:39/255.0 green:174/255.0 blue:96/255.0 alpha:100];
I create a custom tableview cell, and those four button use the same IBAction when the button been pressed. Then change the background color of that button. It works.
TableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 2;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellID = #"cell";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [[NSBundle mainBundle] loadNibNamed:#"TableViewCell" owner:self options:nil][0];
}
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
Button click code
- (IBAction)actionButtonPressed:(UIButton *)sender {
[sender setBackgroundColor:[UIColor redColor]];
}
You don't need to use the layer of the buttons it is enough to set the backgroundColor ( i assume that you are able to access your buttons over cell.Button)
cell.goodButton.backgroundColor = [[UIColor colorWithRed:39/255.0 green:174/255.0 blue:96/255.0 alpha:100] CGColor ];
...
cell.betterButton.backgroundColor = [UIColor clearColor];
cell. bestButton.backgroundColor = [UIColor clearColor];
cell. worstButton.backgroundColor = [UIColor clearColor];

Adding last row cell (that is not part of sqlite table) on tableView

I have this issue on adding a last cell row to my tableView.
Can someone please tell me what's wrong with my code as the last row appears but it also appears elsewhere when the table is scrolled down. Any help will be greatly appreciated, Thank you. Here's my code:
#interface ViewOrderViewController : UIViewController < UITableViewDataSource, UITableViewDelegate> {
IBOutlet UITableView *tabView;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [appDelegate.vieworderArray count] + 1;
}
-(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:#"Cell"];
}
NSUInteger row = [indexPath row];
if(row == [appDelegate.vieworderArray count] ) {
cell.textLabel.text = [NSString stringWithFormat:#"extra cell"];
}else{
Vieworder *vieworderObj = (Vieworder *)[appDelegate.vieworderArray objectAtIndex:indexPath.row];
NSMutableString *mcmenuNameQuantity = [NSMutableString stringWithFormat:#"%# X %i", vieworderObj.mcmenu_name, vieworderObj.mcmenu_quantity];
UILabel *mcmenuLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 0, 200, 25)];
[mcmenuLabel setFont:[UIFont systemFontOfSize:13.0f]];
[mcmenuLabel setText:mcmenuNameQuantity];
UILabel *mcmenuPricexquantity = [[UILabel alloc] initWithFrame:CGRectMake(213, 0, 60, 25)];
[mcmenuPricexquantity setFont:[UIFont systemFontOfSize:12.0f]];
mcmenuPricexquantity.textAlignment = NSTextAlignmentRight;
NSMutableString *mcmenuPriceQuantityString = [NSMutableString stringWithFormat:#"%0.2f", vieworderObj.mcmenu_total_price];
mcmenuPricexquantity.numberOfLines = 2;
[mcmenuPricexquantity setText:mcmenuPriceQuantityString];
UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
deleteButton.frame = CGRectMake(12.0f, 0.0f, 25.0f, 25.0f);
deleteButton.tag = indexPath.row;
UIImage* imageDelete = [[UIImage alloc] init];
imageDelete = [UIImage imageNamed:[NSString stringWithFormat:#"vieworder_delete.png"]];
[deleteButton setImage:imageDelete forState:UIControlStateNormal]
[deleteButton addTarget:self action:#selector(performExpand:) forControlEvents:UIControlEventTouchUpInside];
UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
editButton.frame = CGRectMake(280.0f, 0.0f, 25.0f, 25.0f);
UIImage* imageEdit = [[UIImage alloc] init];
imageEdit = [UIImage imageNamed:[NSString stringWithFormat:#"vieworder_edit.png"]];
[editButton setImage:imageEdit forState:UIControlStateNormal];
editButton.tag = indexPath.row;
[editButton addTarget:self action:#selector(buttonClicked2:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:deleteButton ];
[cell.contentView addSubview:mcmenuLabel];
[cell.contentView addSubview:mcmenuPricexquantity ];
[cell.contentView addSubview:editButton ];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
return cell;
}
Use simplest code first
arr=#[#"A",#"B",#"C",#"D",#"E",#"F",#"A",#"B",#"C",#"D",#"E",#"F",#"A",#"B",#"C",#"D",#"E",#"F",#"A",#"B",#"C",#"D",#"E",#"F",#"A",#"B",#"C",#"D",#"E",#"F",#"A",#"B",#"C",#"D",#"E",#"F"];
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arr count]+1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text=(indexPath.row==arr.count)?#"End of Row":arr[indexPath.row];
return cell;
}
If it is working then then there should be some problem with your else condition where you are adding multiple subviews to cell.ContentView.

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

Resources