You say you don't want to use a XIB and want to do it all programmatically.
You need to implement the initWithFrame:
method:
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame])) {
// create/initialize your subviews here
self.myLabel = [[UILabel alloc] init...];
// configure the label
self.myLabel.font = ...;
self.myLabel.autoresizingMask = ...;
[self addSubview:self.myLabel];
}
return self;
}
So you create and configure your controls (fonts, colours, autoresizing masks etc.) and add them as subviews, all from the initWithFrame:
method. You probably want to break the code out into different methods to keep things clean.
If you are using autolayout, you also want to create all your constraints from the init method.
If you are not using autolayout, you should implement the -layoutSubviews
method. This will be called at appropriate times to layout your subviews (e.g. when the frame of your view changes):
- (void)layoutSubviews
{
self.myLabel.frame = ...;
}
From the layoutSubviews
method you can access self.bounds
to figure out the size of the view at that time. This will let you know how much width/height you have to align or wrap things correctly.
When it comes to creating an instance of your view, just use [[MyCustomView alloc] init]
(which will call initWithFrame:
with an empty rect) or [[MyCustomView alloc] initWithFrame:...]
. Set its frame and add it to some view. The layoutSubviews
method will be called at all the appropriate times and it will be layed out accordingly.