简体   繁体   中英

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 here For 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.

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