0

I am using onegray's Radio button class in one of my projects. the one mentioned here: Best radio-button implementation for IOS

I am using these radio buttons for my answer choices on a quiz. when the user clicks the next button, the labels are populated with new choices. the only problem is that the old ones dont disappear. So when I click next, the new set of buttons are placed on top of the old ones.

what is the simplest way to first check to see if they already exist.. and if so.. delete them.. before displaying the new ones?

here is my code.

@interface LABViewControllerQuiz ()

@end

@implementation LABViewControllerQuiz
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
int  counter =0;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _fileContents = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"quizQuestions" ofType:@"txt"] encoding:NSUTF8StringEncoding error: nil];
    _theScanner = [NSScanner scannerWithString:_fileContents];
    _separator = [NSCharacterSet characterSetWithCharactersInString:@"~"];
    _lineBreak =[NSCharacterSet characterSetWithCharactersInString:@"@"];
    _alreadyGeneratedNumbers =[[NSMutableArray alloc]init];
    _numQuestions =0;
    _userAnswers = [[NSMutableArray alloc]init];
    _answerKey = [[NSMutableArray alloc]init];

    [self nextQuestion:nil];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


- (IBAction)nextQuestion:(UIButton *)sender
{
    _NextQuestionButton.enabled = YES;
    _submitButton.enabled = NO;
    NSLog(@"NumQuestion = %d", _numQuestions);
    if (_numQuestions >9)
    {
        _NextQuestionButton.enabled = NO;
        _submitButton.enabled = YES;
    }else
    {
        int r = arc4random() %20;
        while ([_alreadyGeneratedNumbers containsObject:[NSNumber numberWithInt:r]])
        {
            r = arc4random() %20;
        }
        [_alreadyGeneratedNumbers addObject:[NSNumber numberWithInt:r]];


        while(![_theScanner isAtEnd])
        {
            NSLog(@"Location= %d", [_theScanner scanLocation]);
            NSLog(@"Already Generated numbers:");
            int i =0;
            while (i < [_alreadyGeneratedNumbers count])
            {
                NSLog(@"%@", [_alreadyGeneratedNumbers objectAtIndex:i]);
                i++;
            }

            NSString *line;
            _lineArray = [[NSMutableArray alloc] init];
            [_theScanner scanUpToCharactersFromSet:_lineBreak intoString:&line];
            [_theScanner setCharactersToBeSkipped:_lineBreak];
            NSScanner *inner = [NSScanner scannerWithString:line];
            NSString *word;
            int wordCount = 0;
            NSLog(@"r = %d counter = %d", r, counter);
            if (counter ==r)
            {
                while(![inner isAtEnd])
                {
                    [inner scanUpToCharactersFromSet:_separator intoString:&word];
                    [inner setCharactersToBeSkipped:_separator];
                    [_lineArray insertObject:word atIndex:wordCount];
                    _questionText.text = [NSString stringWithFormat:@"Question %d \n %@", _numQuestions +1,[_lineArray objectAtIndex:0]];
                    wordCount++;
                    [_theScanner setScanLocation:0];
                    counter = 0;

                }

                [sender setHidden:YES];
                NSMutableArray* buttons = [NSMutableArray arrayWithCapacity:4];
                CGRect btnRect = CGRectMake(25, 420, 300, 30);
                for (NSString* optionTitle in @[[_lineArray objectAtIndex:1], [_lineArray objectAtIndex:2], [_lineArray objectAtIndex:3], [_lineArray objectAtIndex:4]])
                {
                    RadioButton* btn = [[RadioButton alloc] initWithFrame:btnRect];
                    [btn addTarget:self action:@selector(onRadioButtonValueChanged:) forControlEvents:UIControlEventValueChanged];
                    btnRect.origin.y += 40;
                    [btn setTitle:optionTitle forState:UIControlStateNormal];
                    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                    btn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
                    [btn setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
                    [btn setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];
                    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
                    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
                    [self.view addSubview:btn];
                    [buttons addObject:btn];
                }


                [buttons[0] setGroupButtons:buttons]; // Setting buttons into the group

                [buttons[0] setSelected:NO]; // Making the first button initially selected

                NSLog(@"the question is = %@", [_lineArray objectAtIndex:0]);
                //NSLog(@"Line arrayINDEX %d = %@", wordCount,[_lineArray objectAtIndex:wordCount]);                _numQuestions ++;
                break;
            }else
            {
                counter ++;
            }

        }
    }
    [_answerKey addObject:[_lineArray objectAtIndex:5]];

}

-(void) onRadioButtonValueChanged:(RadioButton*)sender
{
    // Lets handle ValueChanged event only for selected button, and ignore for deselected
    if(sender.selected)
    {
        NSLog(@"Selected: %@", sender.titleLabel.text);

    }
}
Community
  • 1
  • 1
CDavis10
  • 13
  • 1
  • 5

1 Answers1

0

Save buttons as an instance variable. You're already adding all your buttons into the array, you just throw the array out for some reason.

@interface LABViewControllerQuiz ()
@property (strong) NSMutableArray *buttons;
@end

And then this line:

NSMutableArray* buttons = [NSMutableArray arrayWithCapacity:4];

Becomes these lines:

if (self.buttons) {
  [self.buttons makeObjectsPerformSelector:@selector(removeFromSuperview)];
  [self.buttons removeAllObjects];
} else {
  self.buttons = [NSMutableArray arrayWithCapacity:4];
}
Ian MacDonald
  • 13,472
  • 2
  • 30
  • 51
  • I even put a check at the beginning of the method to see if _buttons has anything in it.. and removes all objects. and it still comes out looking like this: http://gyazo.com/2523960e2c1449f8d45cf7c5df3e476d – CDavis10 Nov 05 '14 at 15:58
  • Are you just removing the objects from the array, or are you also telling each object to be removed from its superview? – Ian MacDonald Nov 05 '14 at 15:59
  • "And then this line: NSMutableArray* buttons = [NSMutableArray arrayWithCapacity:4]; Becomes these lines: if (self.buttons) { [self.buttons makeObjectsPerformSelector:@selector(removeFromSuperview)]; [self.buttons removeAllObjects]; } else { self.buttons = [NSMutableArray arrayWithCapacity:4]; }" <-- that worked... but for some reason my 'next question' button still vanishes. It SHOULD look like this: http://gyazo.com/3c902e4223738830cbac2440308cdd39 – CDavis10 Nov 05 '14 at 16:06
  • but I get this: http://gyazo.com/db33e6e83486be4299ac64356e167f38 notice the absence of the 'Next Question' button – CDavis10 Nov 05 '14 at 16:07
  • Your "next question" button wasn't showing in your earlier screenshot, either. I don't see where you are creating the "next question" button in the source code you linked, leading me to believe that you've simply made a logic error somewhere in your code outside of the scope of this question. – Ian MacDonald Nov 05 '14 at 16:16
  • the button is shown here: gyazo.com/3c902e4223738830cbac2440308cdd39 and it is created in the storyboard. with an outlet and an action associated with it. – CDavis10 Nov 05 '14 at 16:19
  • The earlier screenshot to which I was referring is this one: http://gyazo.com/2523960e2c1449f8d45cf7c5df3e476d – Ian MacDonald Nov 05 '14 at 16:39
  • Oh yes. I noticed that before. but My concern was first dealing with the radio buttons.. THEN figuring out why the next button disappeared after clicking it. basically Its there when the view loads.... but when I click it.. it disappears.. making the user unable to move on to the next question. – CDavis10 Nov 05 '14 at 16:45
  • OMG.... I found it.... derp moment.... [sender setHidden:YES]; I never even noticed that line was there. lol – CDavis10 Nov 05 '14 at 16:56
  • @CDavis10 I also have presbyopia and solved your problem with clip-on, flip-up reader magnifiers, available from multiple online sources. I just took the magnification of my middle trifocal segment, and bought that strength of magnifier. Responding here because your question today was withdrawn. – K7AAY Oct 01 '19 at 00:01