How do I create a custom view class Programmatically?
custom-view, ios, ios6, iphone
Solution
Here is a simple way, hope it helps you.
//in subclassed UIView
#import "CustomView.h"
@implementation CustomView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
// initilize all your UIView components
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(20,30, 200, 44)];
label1.text = @"i am label 1";
[self addSubview:label1]; //add label1 to your custom view
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(20,80, 200, 44)];
label2.text = @"i am label 2";
[self addSubview:label2]; //add label2 to your custom view
[label1 release];//i am using without ARC, comment if u are using ARC
[label2 release];//i am using without ARC, comment if u are using ARC
}
return self;
}
// in your class where u want to use that view
#import "ViewController.h"
#import "CustomView.h"//import it
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//create your view where u want
CustomView *cv = [[CustomView alloc]initWithFrame:CGRectMake(10, 10, 230, 400)]; //create an instance of your custom view
[self.view addSubview:cv]; // add to your main view
[cv release];//comment if u are using ARC
}
Problem
I want to create a very simple customView with a few UIlabel on it, How should i do this . any tutorial or suggestion would be appreciated . I am new to this , didn't try before. I tried this with xib. ``` @interface MyCustomView : UIView @property (strong, nonatomic) IBOutlet UILabel *Label; @end ``` Implementation ``` #import "MyCustomTimer.h" @implementation MyCustomView -(id)initWithCoder:(NSCoder *)aDecoder{ if ((self = [super initWithCoder:aDecoder])){ [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil] objectAtIndex:0]]; } return self; } @end ``` But i need to do it programmatically ,please help . thanks