tags:

views:

34

answers:

1

Hey all, I'm currently teaching myself Objective C and I'm kind of stuck.

I'm building a backgammon game and I have a subclass, "Piece", which is being initialized, repeatedly, in BackGammonViewController.

In BackGammonViewController, if I do this:

UIImage *myImage = [ UIImage imageNamed: @"white-piece.png" ];

UIImageView *myImageView = [ [ UIImageView alloc ] initWithImage: myImage ];
[self.view addSubview:myImageView];
[myImageView release];

The image appears. However, I want to do this within my "piece" class. How do I refer to the "self.view" from within the piece class? Do I need to pass a reference to the view, into the "piece class" ? Or is there a global reference I can call from within the "piece class" ?

Thanks for your help.

+2  A: 

You should avoid reaching across classes like that by accessing your controller's view from the Piece.

Instead, the Piece should be a subclass of UIView which adds the image as a subview to itself when it is inited with a frame:

[self addsubview:myImageView];

You add it as a subview to self because self inherits from UIView. Thus self "IS" a UIView.

Then, just add the piece as a subview of your controller's view.

Chris Cooper
So, in Piece.h, I'd change it to be: "@interface Piece : UIView {", and then in Piece.m do "[self.view addSubview:myImageView];"? This is throwing me an error (error: request for member 'view' in something not a structure or union). Thanks for your help Chris!
thekevinscott
@thekev: My pleasure! See my updated response.
Chris Cooper
Works beautifully!
thekevinscott
@thekev: Great to hear!
Chris Cooper