I need to create several buttons and labels programmatically. For the most part, they will have the same attributes (opaque, backgroundColor, textColor) with the exception of the text, tag, and frame.
While trying to limit the amount of code I needed to type, I figured this would work:
// generate generic properties for our buttons UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; tempButton.opaque = true; tempButton.backgroundColor = [UIColor whiteColor]; tempButton.titleLabel.font = [UIFont fontWithName:@"Helvitica-Bold" size:15];; [tempButton setTitleColor:[UIColor magentaColor] forState:UIControlStateNormal]; [tempButton addTarget:self action:@selector(handleButtonTap:) forControlEvents:UIControlEventTouchUpInside]; // generate specific button1 properties, assign to ivar, and display tempButton.frame = CGRectMake(81, 136, 159, 37); tempButton.tag = BUTTON_1_TAG; [tempButton setTitle:@"button 1 title" forState:UIControlStateNormal]; self.button1 = tempButton; [self.view addSubview:self.button1]; // generate specific button2 properties, assign to ivar, and display tempButton.frame = CGRectMake(81, 254, 159, 37); tempButton.tag = BUTTON_2_TAG; [tempButton setTitle:@"button 2 title" forState:UIControlStateNormal]; self.button2 = tempButton; [self.view addSubview:self.button2];
As most of you already know, only the last button is displaying. I assume this is because all I'm really doing is overwriting tempButton.
Is there a solution that allows me to accomplish what I'm trying to do here, without having to create separate "temp" variables for each element?
Also, it seems like there would be memory leak problems with my code above. My understanding is that tempButton is originally autoreleased, but every time I use it to set my ivar's, isn't it getting retained again? After doing that, would I need to send tempVar a release so it goes back down to 1, so that when autorelease is triggered, it will actually be deallocated?
Thanks for your help!