Giovanni
Giovanni

Reputation: 838

Custom UIView in Code

Ive created a UIView in code using the addSubview:view method. If I want this to be a custom class rather than the standard UIView, does all this customisation have to take place in the view controllers viewDidLoad method? Seems like there will be alot of code in the viewDidLoad if this is the case! This is the first time ive attempted to create a view in code - the other times ive done it in IB where Ive created a custom class and changed the class of the view in the identity inspector.

Upvotes: 0

Views: 143

Answers (1)

danh
danh

Reputation: 62686

Create a new UIView subclass

// MyView.h
@interface MyView : UIView
// public properties, method declarations here
@end

// MyView.m
@implementation MyView
// implementation here, including anything you want to customize this view's
// look or behavior
@end

Then instantiate it in your view controller by importing and referring to the custom class

// ViewController.m
#import "MyView.h"

- (void)viewDidLoad {

    [super viewDidLoad];
    MyView *myView = [[MyView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:myView];
}

Upvotes: 3

Related Questions