Jimmery
Jimmery

Reputation: 10119

Adding subviews to a view from inside another object

I have these two properties defined in my appDelegate:

@property (nonatomic, strong) UIView * mainView;
@property (nonatomic, strong) MyCustomClass * customObj

What is the best way of adding subviews to mainView from code inside customObj?

I am not providing any sample code because (a) my code is terrible and (b) I just want to understand the best approach of doing this, so I can learn from this in the future, rather than having one solution to one specific problem.

Many thanks.

Upvotes: 1

Views: 67

Answers (2)

Tamás Zahola
Tamás Zahola

Reputation: 9321

It depends on what kind of class MyCustomClass is. Is it responsible for building mainView's view hierarchy? Then I'd inject a reference of mainView to customObj, like this:

customObj = [[MyCustomClass alloc] initWithView:mainView];

In this scenario, customObj would be some kind of builder object, that creates the view hierarchy inside mainView. Then I'd use the addSubView: selector inside MyCustomClass:

-(id)initWithView:(UIView*)view{
    if(self = [super init]){
        [view addSubView: ...];
        [view addSubView: ...];
        [view addSubView: ...];
    }
}

Upvotes: 1

Antonio MG
Antonio MG

Reputation: 20410

well, what about creating a method in MyCustomClass like this:

-(void)addSubViewToView:(UIView *)view
{
    [view addSubview:otherView];
}

And then call it like this:

[customObj addSubViewToView:mainView];

Upvotes: 2

Related Questions