如何更改单元格内的按钮颜色取决于用户选择?

时间:2015-08-05 10:58:51

标签: objective-c uitableview uibutton

这是我的按钮,当用户选择按钮时,它将显示另一种颜色。

 UIButton *btnClk=[[UIButton alloc]initWithFrame:CGRectMake(0, 50, 50, 50)];
    [btnClk setTitle:@"Click" forState:UIControlStateNormal];
    btnClk.backgroundColor=[UIColor blackColor];
    [btnClk addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:btnClk];

方法:

   -(void)btnClicked:(UIButton *)click
{

         NSIndexPath *ind1=[NSIndexPath indexPathWithIndex:click.tag];
      NSIndexPath *ind2=[NSIndexPath indexPathWithIndex:click.tag];
    if(ind1==ind2)
    {
       btnClk.backgroundColor=[UIColor colorFromHexString:@"#ffc400"];
    }
    else
    {
        btnClk.backgroundColor=[UIColor blackColor];
    }
}

按钮声明是全局的。

2 个答案:

答案 0 :(得分:0)

您的 ind1 ind2 将始终相同。您尝试比较什么?

我想你想改变代码

  

btnClk .backgroundColor = [UIColor colorFromHexString:@"#ffc400"];

  

点击 .backgroundColor = [UIColor colorFromHexString:@"#ffc400"];

答案 1 :(得分:0)

如果按钮声明是全局的,那么你也可以这样做..我希望它有所帮助..

-(void)btnClicked:(UIButton *)click
{
 UIButton *button = (UIButton *)click;
 if(!button.selected)
 {
   btnClk.backgroundColor=[UIColor colorFromHexString:@"#ffc400"];
    button.selected=YES;
 }
 else
 {
    button.selected=NO;
    btnClk.backgroundColor=[UIColor blackColor];
 }
}