views:

32

answers:

2

I am an objective C newb and relative programming novice in general, so your patience is appreciated. Inside a View Based Application template I am pulling this code out of myNameViewController.m and trying to insert it into a custom class. Everything transitions fine except this: [self.view addSubview:myImage]; I gather this is now calling the addSubview method of myObject, which does not exist....what is the correct way to insert the subview into the current view?

#import "myObject.h"

@implementation myObject

-(void)drawImage{

    CGRect myImageRect = CGRectMake(0.0f, 0.0f, 70.0f, 70.0f);
    UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
    [myImage setImage:[UIImage imageNamed:@"test.png"]];
    myImage.opaque = YES;
    [self.view addSubview:myImage];
}

@end
A: 

The code you have copied is deriving from UIViewController (which is where the view property is defined). addSubview is a message on the UIView object.

So your myObject needs to be a subclass of UIViewController so that you can access its child view, or perhaps myObject is just a view on it's own (does myObject derive from UIView ?), in which case you can just add the UIImageView to the view hierarchy for myObject:

[self addSubview:myImage];

Update

You need to implement the drawRect message in your UIView subclass and draw on context. So something like:

@implementation ViewWhichDrawsItself

- (void)drawRect:(CGRect)rect 
{
    // get the drawing context
    CGContextRef context = UIGraphicsGetCurrentContext ();

    // draw on the context
    ...
}
Cannonade
Hi Cannondale, many thanks for your response. Would you be so kind as to post some example code of a UIView subclass object that can draw itself? I couldn't find any examples on the web or in the Apple documentation about how to do this...thanks again.
Ben
@Ben updated with some sample code
Cannonade
A: 

Your myObject has to be a subclass of UIViewController for this to work, since this will give it the view property (same as the viewController you've copied the code from.

In myObject.h, your interface should read:

@interface myObject : UIViewController {

}

which means that it subClasses, or becomes a UIViewController at heart. It can do anything a regular UIViewController can do and will inherit all the same properties (such as a view), but since it only subclasses it you are able to add extra information that is specific to your own object.

davbryn