开发者

How do I refer to a view controller in a subclass?

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜