如何更改在我们点击它时在表格视图单元格上添加的按钮背景颜色?

时间:2015-09-13 13:52:48

标签: ios swift

我在tableview单元格上添加了一个自定义按钮,一切正常。

但是我的主要要求是当我点击该按钮时,第一次"在表视图单元格中添加,然后按钮背景颜色需要更改(变为红色),当我第二次单击按钮时,需要显示以前的颜色(返回白色)

我的代码:

#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

enter image description here

3 个答案:

答案 0 :(得分:0)

您可以创建一个数组,您可以在其中存储所选按钮。 例如:

var selectedButtons: [Bool] = [Bool](count: N, repeatedValue: false)

在你的cellForRowAtIndexPath中:

if selectedButtons[indexPath.row] {
     yourButton.backgroundColor = UIColor.redColor()
} else {
     yourButton.backgroundColor = UIColor.whiteColor()
}

然后在你的tableView didSelectRowAtIndexPath中你可以说:

selectedButtons[indexPath.row] = true
tableView.reloadData()

抱歉,我的代码在Swift中,但将其转换为Obj-C并不难。

答案 1 :(得分:0)

在cellForRowIndexpath方法中为您的按钮指定一个标记值:

   button.tag=indexPath.row;

并在您的视图中加载,将BOOL作为.m文件中的属性并使其可供整个类访问

   BOOL tapped =NO;

然后在你的按钮操作方法中:

-(IBAction)buttonMethod:(id)sender{

 if(sender.tag==0){

           button.backgroundColor= tapped ? [UIColor whiteColor]:[UIColor redColor];
           tapped = !tapped;
     }
    }

答案 2 :(得分:0)

enter code here对于这样的问题,请使用tableview数据源数组的字典数组。喜欢这个

NSMutableDictionary *datadict = [[NSMutableDictionary alloc] init];
[datadict setObject:@"Your title" forKey:@"Title"];
[datadict setObject:@"N" forKey:@"isSelected"];
[mainArray addObject: datadict]

首次将此代码放入所有标题的循环中,并NisSelected密钥。 那么你的tableview方法特别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;
}

然后在你的按钮操作应该像

-(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"];

    }


}

您还可以在按钮操作中重新加载表以查看效果。保持多行选择以及数据大且实时的良好代码技术。通过这种方式,我们可以在任何事件需要时获取所有选定的行。