Tuesday, 30 September 2014

Add Controls Programatically

It is very easy to Add Controls programmatically we just need to set the frames of controls as per our requirements.

In this post i have added UIView, UIImageView, UILabel, UIButton and UITextField.

- (void)viewDidLoad
{
        [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    
    UIView *dynamicView=[[UIView alloc]initWithFrame:CGRectMake(10, 15, 300, 500)];
    [dynamicView setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:dynamicView];
    
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, 140, 150)];
    [imageView setImage:[UIImage imageNamed:@"audi.png"]];
    [dynamicView addSubview:imageView];
    
    UIImageView *imageView2=[[UIImageView alloc]initWithFrame:CGRectMake(160, 20, 140, 150)];
    [imageView2 setImage:[UIImage imageNamed:@"bmw.png"]];
    [dynamicView addSubview:imageView2];
    
    UILabel *label1=[[UILabel alloc]initWithFrame:CGRectMake(60, 180, 50, 20)];
    [label1 setBackgroundColor:[UIColor clearColor]];
    [label1 setText:@"Audi"];
    [label1 setTextAlignment:UITextAlignmentCenter];
    [label1 setFont:[UIFont systemFontOfSize:20.0f]];
    [dynamicView addSubview:label1];
    
    UILabel *label2=[[UILabel alloc]initWithFrame:CGRectMake(200, 180, 50, 20)];
    [label2 setBackgroundColor:[UIColor clearColor]];
    [label2 setText:@"BMW"];
    [label2 setTextAlignment:UITextAlignmentCenter];
    [label2 setFont:[UIFont systemFontOfSize:20.0f]];
    [dynamicView addSubview:label2];
    
    
    UITextField *textfield=[[UITextField alloc]initWithFrame:CGRectMake(10, 250, 120, 30)];
    [textfield setBorderStyle:UITextBorderStyleRoundedRect];
    [textfield setText:@"Demo Text"];
    [dynamicView addSubview:textfield];
    
    UIButton *dynamicButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [dynamicButton setFrame:CGRectMake(200, 250, 80, 30)];
    [dynamicButton setTitle:@"Click Me" forState:UIControlStateNormal];
    [dynamicButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
    [dynamicView addSubview:dynamicButton];

}

// Method for button 

-(IBAction)buttonClicked;
{
    NSLog(@"Button Clicke Event Called");

}


Thanks & Regards
Angel AppTech

No comments:

Post a Comment

Note: only a member of this blog may post a comment.