如何清除UIButton背景图像状态?

发布于 2024-11-04 02:31:29 字数 8300 浏览 2 评论 0原文

-(void) btnAction:(id) sender {

    NSString *str =((UIButton*)sender).titleLabel.text;

    NSLog(@"%@",str);
    NSLog(@"%@",[dictionary objectForKey:@"option3"]);

    correctAns=[dictionary objectForKey:@"answer"];

        if(str==[dictionary objectForKey:@"option1"])
{

    selectedAns=@"1";

    if ([selectedAns compare:correctAns]==NSOrderedSame) 
    {
     NSLog(@"this is correct");
    [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];

     countCorrect++;
     cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

    else 
    {

        [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option_red.png"] forState:UIControlStateSelected];
        cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

}
}

在 tableView 的初始化中

        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"BeginingCell";

    cell=(BeginingCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];


    if (cell == nil) {

        NSArray *topLevelObjects=[[NSBundle mainBundle] loadNibNamed:@"BeginingCell" owner:self options:nil ];

        for(id CurrentObject in topLevelObjects)
        {
            if ([CurrentObject isKindOfClass:[BeginingCell class]]) {

                cell=(BeginingCell *) CurrentObject;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;


                break;
            }
        }

    }


    if(indexPath.row==0)
    {


       imageURL=[dictionary objectForKey:@"questionImage"];
     //  imageName=[dictionary objectForKey:@"questionImage"];
     // imageURL=@"http://localhost:85/2/";
     // imageURL=[imageURL stringByAppendingString:imageName];

        NSURL *url = [NSURL URLWithString:imageURL];
        NSData *data = [NSData dataWithContentsOfURL:(NSURL *)url];
        UIImage *img = [[UIImage alloc]  initWithData:data];



        cell.lblScoreCurrent.text=[NSString stringWithFormat:@"%d", reloader];

        cell.lblScore.text=@"/30";
        cell.myImageView.image = img;
        cell.SectionTitle.text=[dictionary objectForKey:@"question"];




        [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
        [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState: UIControlStateSelected];
        [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option_red.png"] forState: UIControlStateSelected];
}

随着代码的更改:

这次甚至没有将背景图像从 option.jpg 更改为绿色/红色。在所有单击中它始终是 option.jpg 。

**使用我的代码...我没有收到任何错误... **我用断点进行了测试,它正确地执行了所有语句...甚至图像的更改...但我看不到任何背景图像更改。告诉我接下来是什么...

  -(void) btnAction:(id) sender {

    NSString *str =((UIButton*)sender).titleLabel.text;

NSLog(@"%@",str);
NSLog(@"%@",[dictionary objectForKey:@"option3"]);

correctAns=[dictionary objectForKey:@"answer"];

if([str isEqualToString:([dictionary objectForKey:@"option1"])])

{

    selectedAns=@"1";

    if ([selectedAns isEqualToString:correctAns]) 
    {
     NSLog(@"this is correct");
     [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];

     countCorrect++;
     cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

    else 
    {

        [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];
        cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

}

所有逻辑没问题..即使我正在计算分数..我测试了它...只是这个图像问题不起作用....请告诉我一种方法...我是iPhone新手...学习它..所以如果有任何错误或不好的做法,请给我适当的指示...

使用您的代码后:

代码对于按钮 aciton :

    -(void) btnAction:(id) sender {

((UIButton *)sender).selected=FALSE;
NSString *str =((UIButton*)sender).titleLabel.text;
correctAns=[dictionary objectForKey:@"answer"];

if([str isEqualToString:([dictionary objectForKey:@"option1"])])

{

    selectedAns=@"1";
    NSLog(@"Selected Ans = %@",selectedAns);
    NSLog(@"Correct = %@",correctAns);


    if ([selectedAns isEqualToString:correctAns]) 
    {
     NSLog(@"this is correct");

     [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];

    //  sleep(3);

     countCorrect++;
     cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

    else 
    {

        [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_red.png"] forState:UIControlStateSelected];



        cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

    ((UIButton*)sender).selected = true;

}

tableView Indexpath 中的代码:

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"BeginingCell";

cell=(BeginingCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];


if (cell == nil) {

    NSArray *topLevelObjects=[[NSBundle mainBundle] loadNibNamed:@"BeginingCell" owner:self options:nil ];

    for(id CurrentObject in topLevelObjects)
    {
        if ([CurrentObject isKindOfClass:[BeginingCell class]]) {

            cell=(BeginingCell *) CurrentObject;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;


            break;
        }
    }

}


if(indexPath.row==0)
{


   imageURL=[dictionary objectForKey:@"questionImage"];
 //  imageName=[dictionary objectForKey:@"questionImage"];
 // imageURL=@"http://localhost:85/2/";
 // imageURL=[imageURL stringByAppendingString:imageName];

    NSURL *url = [NSURL URLWithString:imageURL];
    NSData *data = [NSData dataWithContentsOfURL:(NSURL *)url];
    UIImage *img = [[UIImage alloc]  initWithData:data];



    cell.lblScoreCurrent.text=[NSString stringWithFormat:@"%d", reloader];

    cell.lblScore.text=@"/30";
    cell.myImageView.image = img;
    cell.SectionTitle.text=[dictionary objectForKey:@"question"];


    [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
    [cell.ansBtn2 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
    [cell.ansBtn3 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
    [cell.ansBtn4 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];

    cell.ansBtn1.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.ansBtn2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.ansBtn3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.ansBtn4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;



    cell.ansBtn1.titleLabel.textAlignment = UITextAlignmentCenter;
    cell.ansBtn2.titleLabel.textAlignment = UITextAlignmentCenter;
    cell.ansBtn3.titleLabel.textAlignment = UITextAlignmentCenter;
    cell.ansBtn4.titleLabel.textAlignment = UITextAlignmentCenter;


    [cell.ansBtn1 setTitle:[dictionary objectForKey:@"option1"] forState:UIControlStateNormal];
    [cell.ansBtn2 setTitle:[dictionary objectForKey:@"option2"] forState:UIControlStateNormal];
    [cell.ansBtn3 setTitle:[dictionary objectForKey:@"option3"] forState:UIControlStateNormal];
    [cell.ansBtn4 setTitle:[dictionary objectForKey:@"option4"] forState:UIControlStateNormal];


    [cell.ansBtn1 addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.ansBtn2 addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.ansBtn3 addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.ansBtn4 addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];

    [cell.ansBtn1 addTarget:self action:@selector(btnActionUp:) forControlEvents:UIControlEventTouchDown];

    //cell.ansBtn1.showsTouchWhenHighlighted=TRUE;
    cell.ansBtn2.showsTouchWhenHighlighted=TRUE;
    cell.ansBtn3.showsTouchWhenHighlighted=TRUE;
    cell.ansBtn4.showsTouchWhenHighlighted=TRUE;



}


return cell;

}

-(void) btnAction:(id) sender {

    NSString *str =((UIButton*)sender).titleLabel.text;

    NSLog(@"%@",str);
    NSLog(@"%@",[dictionary objectForKey:@"option3"]);

    correctAns=[dictionary objectForKey:@"answer"];

        if(str==[dictionary objectForKey:@"option1"])
{

    selectedAns=@"1";

    if ([selectedAns compare:correctAns]==NSOrderedSame) 
    {
     NSLog(@"this is correct");
    [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];

     countCorrect++;
     cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

    else 
    {

        [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option_red.png"] forState:UIControlStateSelected];
        cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

}
}

in Initialization of tableView

        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"BeginingCell";

    cell=(BeginingCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];


    if (cell == nil) {

        NSArray *topLevelObjects=[[NSBundle mainBundle] loadNibNamed:@"BeginingCell" owner:self options:nil ];

        for(id CurrentObject in topLevelObjects)
        {
            if ([CurrentObject isKindOfClass:[BeginingCell class]]) {

                cell=(BeginingCell *) CurrentObject;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;


                break;
            }
        }

    }


    if(indexPath.row==0)
    {


       imageURL=[dictionary objectForKey:@"questionImage"];
     //  imageName=[dictionary objectForKey:@"questionImage"];
     // imageURL=@"http://localhost:85/2/";
     // imageURL=[imageURL stringByAppendingString:imageName];

        NSURL *url = [NSURL URLWithString:imageURL];
        NSData *data = [NSData dataWithContentsOfURL:(NSURL *)url];
        UIImage *img = [[UIImage alloc]  initWithData:data];



        cell.lblScoreCurrent.text=[NSString stringWithFormat:@"%d", reloader];

        cell.lblScore.text=@"/30";
        cell.myImageView.image = img;
        cell.SectionTitle.text=[dictionary objectForKey:@"question"];




        [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
        [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState: UIControlStateSelected];
        [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option_red.png"] forState: UIControlStateSelected];
}

With changes with your code:

This time it's not even changing the background image from option.jpg to green/red.It's always option.jpg in all click.

**And with my code...i didn't get any error...
*
*I tested with break point it's going through all the statement properly...even the change of image..but i can't see any backgroud image change.Tell me what is next...

  -(void) btnAction:(id) sender {

    NSString *str =((UIButton*)sender).titleLabel.text;

NSLog(@"%@",str);
NSLog(@"%@",[dictionary objectForKey:@"option3"]);

correctAns=[dictionary objectForKey:@"answer"];

if([str isEqualToString:([dictionary objectForKey:@"option1"])])

{

    selectedAns=@"1";

    if ([selectedAns isEqualToString:correctAns]) 
    {
     NSLog(@"this is correct");
     [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];

     countCorrect++;
     cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

    else 
    {

        [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];
        cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

}

All the logic are ok..even i am calculating the score..i tested it...just this image issue is not working....please show me a way.....i am totally new in iphone....learning it..so please give me proper instruction if anything is wrong or bad practice...

After using your code :

Code for the button aciton :

    -(void) btnAction:(id) sender {

((UIButton *)sender).selected=FALSE;
NSString *str =((UIButton*)sender).titleLabel.text;
correctAns=[dictionary objectForKey:@"answer"];

if([str isEqualToString:([dictionary objectForKey:@"option1"])])

{

    selectedAns=@"1";
    NSLog(@"Selected Ans = %@",selectedAns);
    NSLog(@"Correct = %@",correctAns);


    if ([selectedAns isEqualToString:correctAns]) 
    {
     NSLog(@"this is correct");

     [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];

    //  sleep(3);

     countCorrect++;
     cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

    else 
    {

        [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_red.png"] forState:UIControlStateSelected];



        cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];

    }

    ((UIButton*)sender).selected = true;

}

code in the tableView Indexpath :

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"BeginingCell";

cell=(BeginingCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];


if (cell == nil) {

    NSArray *topLevelObjects=[[NSBundle mainBundle] loadNibNamed:@"BeginingCell" owner:self options:nil ];

    for(id CurrentObject in topLevelObjects)
    {
        if ([CurrentObject isKindOfClass:[BeginingCell class]]) {

            cell=(BeginingCell *) CurrentObject;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;


            break;
        }
    }

}


if(indexPath.row==0)
{


   imageURL=[dictionary objectForKey:@"questionImage"];
 //  imageName=[dictionary objectForKey:@"questionImage"];
 // imageURL=@"http://localhost:85/2/";
 // imageURL=[imageURL stringByAppendingString:imageName];

    NSURL *url = [NSURL URLWithString:imageURL];
    NSData *data = [NSData dataWithContentsOfURL:(NSURL *)url];
    UIImage *img = [[UIImage alloc]  initWithData:data];



    cell.lblScoreCurrent.text=[NSString stringWithFormat:@"%d", reloader];

    cell.lblScore.text=@"/30";
    cell.myImageView.image = img;
    cell.SectionTitle.text=[dictionary objectForKey:@"question"];


    [cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
    [cell.ansBtn2 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
    [cell.ansBtn3 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
    [cell.ansBtn4 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];

    cell.ansBtn1.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.ansBtn2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.ansBtn3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.ansBtn4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;



    cell.ansBtn1.titleLabel.textAlignment = UITextAlignmentCenter;
    cell.ansBtn2.titleLabel.textAlignment = UITextAlignmentCenter;
    cell.ansBtn3.titleLabel.textAlignment = UITextAlignmentCenter;
    cell.ansBtn4.titleLabel.textAlignment = UITextAlignmentCenter;


    [cell.ansBtn1 setTitle:[dictionary objectForKey:@"option1"] forState:UIControlStateNormal];
    [cell.ansBtn2 setTitle:[dictionary objectForKey:@"option2"] forState:UIControlStateNormal];
    [cell.ansBtn3 setTitle:[dictionary objectForKey:@"option3"] forState:UIControlStateNormal];
    [cell.ansBtn4 setTitle:[dictionary objectForKey:@"option4"] forState:UIControlStateNormal];


    [cell.ansBtn1 addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.ansBtn2 addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.ansBtn3 addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.ansBtn4 addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];

    [cell.ansBtn1 addTarget:self action:@selector(btnActionUp:) forControlEvents:UIControlEventTouchDown];

    //cell.ansBtn1.showsTouchWhenHighlighted=TRUE;
    cell.ansBtn2.showsTouchWhenHighlighted=TRUE;
    cell.ansBtn3.showsTouchWhenHighlighted=TRUE;
    cell.ansBtn4.showsTouchWhenHighlighted=TRUE;



}


return cell;

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别想她 2024-11-11 02:31:29

我仍然不完全理解你的问题..如果你想要一个按钮的正常图像,以及用户触摸按钮时的另一个图像,你可以在创建按钮本身时直接提供它们..单击按钮时无需更改图像..

[cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
[cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState: UIControlStateHighlighted];
[cell.ansBtn2 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
[cell.ansBtn2 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState: UIControlStateHighlighted];
[cell.ansBtn3 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
[cell.ansBtn3 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState: UIControlStateHighlighted];
[cell.ansBtn4 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
[cell.ansBtn4 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState: UIControlStateHighlighted];

由于您已经使用了按钮的突出显示状态,我假设您仅在用户手放在按钮上时才需要绿色图像(即,当用户释放按键时更改为正常图像......)。在这种情况下,上面的代码将起作用......

但是如果您希望按钮图像即使在用户释放后也保持绿色,那么您应该使用 UIButton 的 selected (UIControlStateSelected) 属性..

编辑:看到评论后..

在这种情况下,当按钮分配和 init 只给出正常状态图像..

[cell.ansBtn setBackgroundImage:[UIImage imageNamed:@"option.png" forState:UIControlStateNormal]];

并单击按钮。

-(void)optionButtonClicked:(UIButton*)sender{
   if(correct){
     // green image..
     [sender setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];
   }else{//red image
     [sender setBackgroundImage:[UIImage imageNamed:@"option_red.png"] forState:UIControlStateSelected];
   }
   sender.selected = true;
}

第二次编辑:看到编辑后的问题

首先,永远不要像这样比较两个字符串..

 if(str==[dictionary objectForKey:@"option1"])

而是使用compare()函数或isEqualToString()函数进行比较..

第二件事,您正在使用“< btnAction 函数中的“strong>cell”。我不敢相信它在编译时没有显示“单元未声明”错误。
第三,纠正以上两个错误。
第四,纠正错误后尝试使用断点调试代码。你已经尝试过了吗?在 btnAction 函数中放置一个断点,看看它是否按照您想要的方式执行。然后用您的观察更新这个问题。目前,您的代码中有很多错误,所以我无法判断哪个错误导致了什么..对我来说,这段代码根本不应该被编译..

第三次编辑:只是事后的想法
试试这个..

-(void) btnAction:(id) sender {
   ((UIButton*)sender).selected = FALSE; 
    NSString *str =((UIButton*)sender).titleLabel.text;
    NSLog(@"%@",str);
    NSLog(@"%@",[dictionary objectForKey:@"option3"]);
    correctAns=[dictionary objectForKey:@"answer"];
    if([str isEqualToString:([dictionary objectForKey:@"option1"])]){
       selectedAns=@"1";
       If ([selectedAns compare:correctAns]==NSOrderedSame) {
          NSLog(@"this is correct");
          [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];
          countCorrect++;
        //  cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect]; 

        }else {
           [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_red.png"] forState:UIControlStateSelected];
           cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];
         }
         ((UIButton*)sender).selected = true;
    }
}

第四次编辑:又一个事后想法

-(void) btnAction:(id) sender {
    NSString *str =((UIButton*)sender).titleLabel.text;
    NSLog(@"%@",str);
    NSLog(@"%@",[dictionary objectForKey:@"option3"]);
    correctAns=[dictionary objectForKey:@"answer"];
    if([str isEqualToString:([dictionary objectForKey:@"option1"])]){
       selectedAns=@"1";
       If ([selectedAns compare:correctAns]==NSOrderedSame) {
          NSLog(@"this is correct");
          [((UIButton*)sender) setImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateNormal];
          countCorrect++;
        //  cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect]; 

        }else {
           [((UIButton*)sender) setImage:[UIImage imageNamed:@"option_red.png"] forState:UIControlStateNormal];
           cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];
         }
    }
}

I still dont fully understood your question..If you want one normal image for button , and another when user touches the button, you can give them directly when you create the button itself..No need to change the image when button click..

[cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
[cell.ansBtn1 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState: UIControlStateHighlighted];
[cell.ansBtn2 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
[cell.ansBtn2 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState: UIControlStateHighlighted];
[cell.ansBtn3 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
[cell.ansBtn3 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState: UIControlStateHighlighted];
[cell.ansBtn4 setBackgroundImage:[UIImage imageNamed:@"option.png"] forState: UIControlStateNormal];
[cell.ansBtn4 setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState: UIControlStateHighlighted];

Since you have used highlighted state of the button, I presume you want green image only when users hand is on the button (ie change to normal image when user releases the key..).In that case above code will work..

But if you want button image to remain green even after user releases then you should use selected (UIControlStateSelected) property of UIButton..

Edit:After seeing the comment..

In that case, when button alloc and init only give normal state image..

[cell.ansBtn setBackgroundImage:[UIImage imageNamed:@"option.png" forState:UIControlStateNormal]];

and on button click.

-(void)optionButtonClicked:(UIButton*)sender{
   if(correct){
     // green image..
     [sender setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];
   }else{//red image
     [sender setBackgroundImage:[UIImage imageNamed:@"option_red.png"] forState:UIControlStateSelected];
   }
   sender.selected = true;
}

Second Edit: After seeing the edited question

First thing first, Never compare between two strings like this..

 if(str==[dictionary objectForKey:@"option1"])

Instead compare using compare() function or isEqualToString() function..

Second thing, You are using "cell" in the btnAction function. I cant believe it is not showing "cell is undeclared" error in compile time.
Third, correct above two errors.
Fourth,After correcting the error try to debug your code using breakpoints. Have you tried that already? Put a breakpoint in the btnAction function and see if it is executing the way you want..Then update this question with your observations..At the moment, there are so much errors in your code so that I cant tell which one is causing what..To me this code shouldnt get compiled at all..

Third Edit:Just an afterthought
try this ..

-(void) btnAction:(id) sender {
   ((UIButton*)sender).selected = FALSE; 
    NSString *str =((UIButton*)sender).titleLabel.text;
    NSLog(@"%@",str);
    NSLog(@"%@",[dictionary objectForKey:@"option3"]);
    correctAns=[dictionary objectForKey:@"answer"];
    if([str isEqualToString:([dictionary objectForKey:@"option1"])]){
       selectedAns=@"1";
       If ([selectedAns compare:correctAns]==NSOrderedSame) {
          NSLog(@"this is correct");
          [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateSelected];
          countCorrect++;
        //  cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect]; 

        }else {
           [((UIButton*)sender) setBackgroundImage:[UIImage imageNamed:@"option_red.png"] forState:UIControlStateSelected];
           cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];
         }
         ((UIButton*)sender).selected = true;
    }
}

Fourth EDIT : one more afterthought

-(void) btnAction:(id) sender {
    NSString *str =((UIButton*)sender).titleLabel.text;
    NSLog(@"%@",str);
    NSLog(@"%@",[dictionary objectForKey:@"option3"]);
    correctAns=[dictionary objectForKey:@"answer"];
    if([str isEqualToString:([dictionary objectForKey:@"option1"])]){
       selectedAns=@"1";
       If ([selectedAns compare:correctAns]==NSOrderedSame) {
          NSLog(@"this is correct");
          [((UIButton*)sender) setImage:[UIImage imageNamed:@"option_green.png"] forState:UIControlStateNormal];
          countCorrect++;
        //  cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect]; 

        }else {
           [((UIButton*)sender) setImage:[UIImage imageNamed:@"option_red.png"] forState:UIControlStateNormal];
           cell.lblRating.text=[NSString stringWithFormat:@"%i", countCorrect];
         }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文