Как очистить UIButton background image State? - PullRequest
0 голосов
/ 30 апреля 2011
-(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 на green / red. Это всегда 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;

}

код в табличном виде 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;

}

1 Ответ

0 голосов
/ 30 апреля 2011

Я все еще не до конца понял ваш вопрос. Если вам нужно одно нормальное изображение для кнопки, а другое, когда пользователь касается кнопки, вы можете дать их непосредственно при создании самой кнопки. Не нужно менять изображение, когда кнопка нажмите ..

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

Поскольку вы использовали выделенное состояние кнопки, я предполагаю, что вы хотите, чтобы зеленое изображение отображалось только тогда, когда на кнопке находится пользовательская рука (т. Е. Переходите к обычному изображению, когда пользователь отпускает клавишу ...). В этом случае приведенный выше код будет работать. .

Но если вы хотите, чтобы изображение кнопки оставалось зеленым даже после выпуска пользователя, вам следует использовать свойство selected (UIControlStateSelected) UIButton.

Редактировать: увидев комментарий ..

В том случае, когда кнопка alloc и 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"])

Вместо этого сравните, используя функцию сравнения () или функцию isEqualToString ().

Во-вторых, вы используете " cell " в функции btnAction. Я не могу поверить, что во время компиляции не отображается ошибка « ячейка не объявлена ​​». В-третьих, исправьте две ошибки. В-четвертых, после исправления ошибки попробуйте отладить код с помощью точек останова. Вы уже пробовали это? Поместите точку останова в функцию 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];
         }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...