简体   繁体   中英

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".

  1. 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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM