добавление uibuttons программно - PullRequest
2 голосов
/ 01 июня 2011

здесь у меня есть этот код, который я пытаюсь, где openingHoursView.ohLocation имеет два значения " value1 " и " value2 ".Как и openingHoursView.idNum со значениями " id1 " и " id2 ".Когда я выполняю свой код, я получаю только одну кнопку с именем « value2 » и « id2 ».Поэтому мой вопрос заключается в том, как создать все кнопки для значений openingHoursView.ohLocation и 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'
}

Просто объяснение objectAtIndex: 0 для opensHoursView.ohLocation равно " value1 "и для objectAtIndex: 1 равно" value2".Та же процедура для открытияHoursView.idNum

Ответы [ 3 ]

3 голосов
/ 01 июня 2011

Вы создаете новый вид для каждой кнопки в

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

Поместите этот код перед циклом for.

3 голосов
/ 01 июня 2011

Проблема в том, что вы делаете:

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

self.view.backgroundColor = [UIColor whiteColor];

внутри цикла for и, таким образом, перезаписывается при каждой итерации. Вы должны сделать это только один раз перед циклом for.

2 голосов
/ 03 августа 2012

UIButton *button = [[UIButton alloc] init]; [self. view addubView: кнопка];

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...