How to add subviews in iphone application with example code

Leave a Comment
Here I am giving you complete  example of subviews in iphone . Here I am exaplaining you how to add multiple subviews in single views.

Step 1:
          In viewcontroller.xib file  already one view is there. take two views from object library and put them in xib file with their single own button. So it will look like this ..
 
Step 2:  here you can see that two buttons are txtbutton and lblbuttonlilview. Generate both buttons action event . In viewdidload() method set first view like this.

    [self.view addSubview:lalelview];
    self.navigationController.navigationBarHidden = YES;
    y = self.view.center.y;

 both button events:

- (IBAction)lblbuttonview:(id)sender {
    [txtview removeFromSuperview];
    [self.view addSubview:lalelview];
}
- (IBAction)txtbuttonview:(id)sender {
    [lalelview removeFromSuperview];
    [self.view addSubview:txtview];
}
When you tapped one button it will add first subview .

 Tapped now another button it will add another view and remove previous view.
Here i am giving both files.
ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
 
float y;
 
}
@property (strong, nonatomic) IBOutlet UIView *lalelview;
@property (strong, nonatomic) IBOutlet UIView *txtview;
-(IBAction)lblbuttonview:(id)sender;
-(IBAction)txtbuttonview:(id)sender;
@end

ViewController.m


#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize lalelview;
@synthesize txtview;
- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    [self.view addSubview:lalelview];
    self.navigationController.navigationBarHidden = YES;
    y = self.view.center.y;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)lblbuttonview:(id)sender {
    [txtview removeFromSuperview];
    [self.view addSubview:lalelview];
}
- (IBAction)txtbuttonview:(id)sender {
    [lalelview removeFromSuperview];
    [self.view addSubview:txtview];
}
@end

Please give your reviews if you like and need any help just leave comment only or mail me on devang9978@gmail.com
Devang Patel
(By www.techstudy.net)

0 comments:

Post a Comment