4

In my app I need to add a UIView dynamically whenever user taps on a button in my main UIViewController. How can I do this?

Kevin
  • 14,655
  • 24
  • 74
  • 124
iphoneStruggler
  • 123
  • 2
  • 3
  • 10

1 Answers1

8

Create a new method in your view controller with this signature: -(IBAction) buttonTapped:(id)sender. Save your file. Go to Interface Builder and connect your button to this method (control-click and drag from your button to the view controller [probably your File's owner] and select the -buttonTapped method). Then implement the method:

-(IBAction) buttonTapped:(id)sender {
    // create a new UIView
    UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(10,10,100,100)];

    // do something, e.g. set the background color to red
    newView.backgroundColor = [UIColor redColor];

    // add the new view as a subview to an existing one (e.g. self.view)
    [self.view addSubview:newView];

    // release the newView as -addSubview: will retain it
    [newView release];
}
Björn Marschollek
  • 9,899
  • 9
  • 40
  • 66