以编程方式添加uibutton

时间:2011-06-01 11:38:46

标签: iphone uibutton

这里我有这个代码,我正在尝试在哪里 openingHoursView.ohLocation有两个值“ value1 ”和“ value2 ”。 openingHoursView.idNum的值为“ id1 ”和“ id2 ”也是如此。 当我执行我的代码时,我只得到一个名为“ value2 ”和“ id2 ”的按钮。所以我的问题是如何为openingHoursView.ohLocationopeningHoursView.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 ”。与OpeningHoursView.idNum相同的程序

3 个答案:

答案 0 :(得分:3)

问题在于你在做什么:

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

self.view.backgroundColor = [UIColor whiteColor];

for循环内部,因此在每次迭代时都会被覆盖。您应该只在for循环之前执行一次。

答案 1 :(得分:3)

您正在为

中的每个按钮创建一个新视图
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

将此代码放在for循环之前。

答案 2 :(得分:2)

UIButton * button = [[UIButton alloc] init]; [selfview addsubView:button];