2

here i have this code that i'm trying where openingHoursView.ohLocation has two values "value1" and "value2". So does openingHoursView.idNum with values "id1" and "id2". When i execute my code I only get one button with the name of "value2" and "id2". So my question would be how to create all the buttons for the values of openingHoursView.ohLocation and openingHoursView.idNum

- (void)loadView {

    storeAppDelegate = (StoreAppDelegate *)[[UIApplication sharedApplication] delegate];    

    int row = [storeAppDelegate.openingHoursLocationsDelegate count]-1;
    for (int i = 0; i <= row; i++) {
        openingHoursView = [storeAppDelegate.openingHoursLocationsDelegate objectAtIndex:i];

        self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

        self.view.backgroundColor = [UIColor whiteColor];

        //create the button
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        //set the position of the button
        if (i%2 != 0) {
            button.frame = CGRectMake(30 , 100 , 150, 30);

        }else {
            button.frame = CGRectMake(30 , 100 + i*50, 150, 30);
        }


        //set the button's title
        [button setTitle:openingHoursView.ohLocation forState:UIControlStateNormal];

        //listen for clicks
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = [openingHoursView.idNum intValue];
        //add the button to the view
        [self.view addSubview:button];
    }
}

-(IBAction) buttonPressed: (id) sender {
    UIButton* button = (UIButton*)sender;

    NSLog(@"User clicked %d", button.tag);
    // Do something here with the variable 'sender'
}

Just an explanation objectAtIndex:0 for openingHoursView.ohLocation is "value1" and for objectAtIndex:1 is "value2". Same procedure for openingHoursView.idNum

3 Answers 3

3

The problem is that you're doing:

self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

self.view.backgroundColor = [UIColor whiteColor];

inside the for loop and thus gets overwritten on each iteration. You should only do it once before the for loop.

Sign up to request clarification or add additional context in comments.

Comments

3

You are creating a new view for every button in

self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

Put this code before the for loop.

Comments

2

UIButton *button = [[UIButton alloc]init]; [self.view addsubView:button];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.