簡體   English   中英

如何清除UIButton背景圖片State?

[英]How to clear UIButton background image State?

-(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 中是全新的...... ..學習它..所以如果有什么錯誤或不好的做法,請給我適當的指導......

使用您的代碼后:

按鈕動作的代碼:

    -(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 索引路徑中的代碼:

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

}

我仍然不完全理解您的問題..如果您想要一個正常的按鈕圖像,而另一個當用戶觸摸按鈕時,您可以在創建按鈕本身時直接提供它們..單擊按鈕時無需更改圖像..

[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];

由於您使用了按鈕的突出顯示 state,我假設您僅在用戶手放在按鈕上時才想要綠色圖像(即當用戶釋放鍵時更改為正常圖像..)。在這種情況下,上面的代碼將起作用..

但是,如果您希望按鈕圖像即使在用戶釋放后仍保持綠色,那么您應該使用 UIButton 的 selected (UIControlStateSelected) 屬性。

編輯:看到評論后..

在這種情況下,當按鈕分配和初始化只給出正常的 state 圖像..

[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() function 或 isEqualToString() function 進行比較。

第二件事,您在 btnAction function 中使用“單元格”。 我不敢相信它在編譯時沒有顯示“單元格未聲明”錯誤。 第三,糾正以上兩個錯誤。 第四,糾正錯誤后嘗試使用斷點調試代碼。 你已經試過了嗎? 在 btnAction function 中放置一個斷點,看看它是否按照你想要的方式執行。然后用你的觀察更新這個問題。目前,你的代碼中有很多錯誤,所以我不知道是哪一個導致了什么..對我來說,這段代碼根本不應該被編譯..

第三次編輯:只是事后嘗試這個..

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM