Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a UIView as a subview of UIViewController when a button clicked?

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?

like image 319
iphoneStruggler Avatar asked Feb 27 '23 00:02

iphoneStruggler


1 Answers

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];
}
like image 59
Björn Marschollek Avatar answered Apr 06 '23 00:04

Björn Marschollek