2
votes

I'm trying to create a UIButton programmatically. I have a button called "addCash" (which was already created in interface builder), upon tapping this button I want another button to dynamically appear. This button works fine when done in viewDidLoad, but this is not what I want as "addCash" needs to be tapped before this new button is to be created. This is what I have so far...

-(IBAction) addCash{
UIButton *theButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
theButton.frame = CGRectMake(80, 50, 150, 40);
[theButton setTitle:@"title" forState:UIControlStateNormal];
[theButton addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];
[theButton setBackgroundImage:[UIImage imageNamed:@"edit.jpg"] forState:UIControlStateNormal];

[self.view addSubview:theButton]; 
}
1
Why create the button programmatically? Why not have it created in IB beforehand but with hidden = YES, and just unhide it when your first button is pressed? - yuji
You are leaking theButton. Why are you retaining it? - eric.mitchell
also why have you left out the sender from the method signature? i.e. -(IBAction) addCash:(id)sender {...} ?? - bennythemink
I need to create the button programmatically because ultimately I plan to have an unknown number of buttons created (1 to 100) - SNV7
@bennythemink adding sender is not required and if you don't use the value then why bother... - Paul.s

1 Answers

1
votes

If you plain add a lot of buttons use UITableView with custom cell. If you will just add new buttons to view you will get a performance issue - all you buttons will be loaded simultaneously. UITableView can manage this situation and unload unused cell's.