Saturday, January 07, 2012

iOS: View Programming


Eg.:
UILabel *label = [[UILabel alloc] init];
CGRect bounds = CGRectMake(10, 20, 300, 200);
[label setText:@"This is a label"]; // put some text, if not, nothing seen on screen
[label setFrame:bounds];
[self.view addSubview:label];

// loading image
UIImage *img = [UIImage imageNamed:@"image.jpg"];    
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
// add to view with the same steps as above
...
// set color
[self.view setBackgroundColor:[UIColor colorWithRed:0.1 green:0.7 blue:0.3 alpha:1]];
Note:
UIButton has a class method to create a button. [UIButton buttonWithType:UIButtonTypeRoundedRect]

To programmatically add an action to a button, use addTarget:action:forControlEvents: of the UIControl
Example:
[button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
...
-(void) btnPressed:(id) sender
{
   UIButton *btn = (UIButton *) sender;
   if([btn.titleLabel.text isEqual:@"button label"])
   {
      // code to do something
   }
}

// to remove
[self.view removeFromSuperview];

To load and display a ViewController from XIB file

Screen01ViewController.m
Screen02ViewController *next = [[Screen02ViewController alloc] initWithNibName:@"Screen02ViewController" bundle:nil];    
[self.view addSubview:next.view]; // will put the new view on top of this current view
...

Screen02ViewController.m
[self.view removeFromSuperview]; // if you are done with this view and wants to close it

No comments: