Reputation: 387
I want to create a UIView in classB calling from classA to show on MainView(my UIViewController).
can anyone help me to fix my code?
classA:
+ (void)trigger
{
[classB viewOn:[MainView new]];
}
classB:
+ (void)viewOn:(id)sender
{
MainView *pointer = (MainView *)sender;
classB *view = [[classB alloc] initWithFrame:CGRectMake(380, 200, 100, 50)];
view.backgroundColor = [[UIColor greenColor] colorWithAlphaComponent:0.5f];
view.userInteractionEnabled = YES;
UILabel *lab = [UILabel new];
lab.frame = CGRectMake(0, 0, 100, 50);
lab.text = @"test";
[view addSubview:lab];
[pointer.view addSubview:view];
}
When I use MainView class to call classB by [classB viewOn:self] it works fine. But if I want to trigger it from classA, how can I do?
Upvotes: 2
Views: 356
Reputation: 11
Use delegation.
It is quite simple.
All you have to do is go to ClassA
.
Make it look like this
@interface ClassA: NSObject <ClassB>
and now you can call it from ClassA
.
Hope I helped as I am kind of new to objective-c.
Upvotes: 0
Reputation: 124997
When I use MainView class to call classB by [classB viewOn:self] it works fine.
That's because you're casting sender
to a MainView *
.
But if I want to trigger it from classA, how can I do?
If you want to do the same thing from ClassA, you'll need a pointer to an instance of MainView to pass in. I see that you're trying to do that already...
[classB viewOn:[MainView new]];
That's probably not the right way to initialize your MainView, though... views are generally initialized with alloc
followed by initWithFrame:
.
Before you spend too much time trying to make this all work, you should think about the different roles your objects are playing here. Normally, you'd use a view controller to manage the creation and configuration of your view hierarchy. One way that a view controller would be useful here is to keep a reference to your instance of MainView. Your view controller could then instantiate ClassB and add that new view to MainView. You seem to be trying to make your ClassA work as a view controller as well as a view -- that's probably just going to muddy the waters and make it more difficult for you to learn to work effectively in Objective-C and Cocoa Touch.
Upvotes: 1