views:

156

answers:

3

I am trying to programmatically change the user interface of a UIViewController from another NSObject class. The problem is that I am unsure of how to access the UIViewController's view from the NSObject class. So for example, in my NSObject class, I say something like:

self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
self.view.backgroundColor = [UIColor yellowColor];

but I keep getting errors saying "Request for member "view" in something not a strut or union." Is there something I need to allow my NSObject class to see my UIViewController? Thanks!

A: 

you can't access like this... you need to somehow pass UIViewController's view in your NSObject class...

mihirpmehta
+1  A: 

Whenever you say "self" in a method, it refers to whatever object owns that method. So when you say self.view, you are really asking for the NSObject's view (which, needless to say, doesn't exist, unless you have specifically subclassed the NSObject to have a "view" property.

What you should do is give the NSObject class a property called myController or something in its interface declaration, or pass a ViewController* to any methods that need to access it.

For the property, you can say:

ViewController* myController;

in the NSObject sub-class interface declaration, or for the method way, add an argument to your NSObject sub-class' method:

- (void) someMethodThatTakesAViewController: (ViewController*) theViewController {
    //Do your stuff here
    theViewController.view = [[UIView alloc] init]; // Or whatever you want to do
} 

Hope this was what you were looking for.

Chris Cooper
A: 

In the header file for the object that is trying to change the view, add @class <YOURVIEWCONTROLLER>;, then in the @interface section, add <YOURVIEWCONTROLLER> *viewController; then outside @interface add @property (nonatomic, retain) <YOURVIEWCONTROLLER> *viewController;. Then in the main file add @synthesize viewController; and #import "<YOURVIEWCONTROLLER.h". Then, to change the background colour, use viewController.view.backgroundColor = [UIColor <COLOUR>];.

e.g:

Test.h:

#import <UIKit/UIKit.h>

@class Test2ViewController;

@interface Test : UIViewController {
    Test2ViewController *viewController;
}

@property (nonatomic, retain) Test2ViewController *viewController;

Test.m:

#import "Test.h"
#import "Test2ViewController.h"

@implementation Test

@synthesize viewController;

...

viewController.view.backgroundColor = [UIColor yellowColor];

...

Hope this helps

Edit: Make sure to call [viewController release] in your dealloc, otherwise you will have a leaky pipe ;)

jrtc27