Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a [self.view addSubview: lbl] outside of ViewController Class scope?

How to perform a [self.view addSubview: lbl] outside of ViewController Class scope ?

or:

How do I add a label or another view in the mainview, outside of the ViewController class, in a different class?

thanks

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
    [lbl setText:@"hi there"];

    [self.view addSubview:lbl];// <-- this works, but ...
        // what is "self" referring to? 
        // and how can I declare and call from another class? 

    ...


    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
    [lbl setText:@"hi there"];

    calcRomanAppDelegate *v = [[calcRomanAppDelegate new] init]; 
    [v.viewController.view addSubview:lbl]; // this compiles, but...
         // fails to shows a label on the form

     ...


    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 
    [lbl setText:@"hi there"];

    calcRomanViewController *v = [[calcRomanViewController new] init];
    [v.view addSubview:lbl]; // this just makes a call back to viewDidLoad... endless loop

}
like image 619
jdl Avatar asked Jan 22 '26 14:01

jdl


2 Answers

Well, view is just a property of the UIViewController class. Assuming that you have your UIViewController *controller variable somewhere, you can just use

[controller.view addSubview:subview]
like image 146
Anton Avatar answered Jan 25 '26 03:01

Anton


The reason that [v.viewController.view addSubview:lbl]; doesn't work is that v is a new instance of calcRomanAppDelegate. Every application has a shared instance of the app delegate, that can be accessed via [[NSApplication sharedApplication] delegate]. Therefore, your code would become:

calcRomanAppDelegate *v = (calcRomanAppDelegate *)[[NSApplication sharedApplication] delegate]; 
[v.viewController.view addSubview:lbl]; // this compiles but shows a blank form

Also In the code that you wrote, I will point out that the new method returns an initialized object, so you do not need the extra call to init in [[calcRomanAppDelegate new] init]. Instead of using the new method, I suggest using alloc, which doesn't call the initializer. Obviously that is not the issue in this particular case, but it's an important thing to know.

like image 40
Alex Nichol Avatar answered Jan 25 '26 03:01

Alex Nichol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!