我有两个类:MainViewController和PlayerImageController(NSObject)
我如何能够将我的UIImageView的子视图从PlayerImageController添加到我的MainViewController并指示像
这样的动作- (void)viewDidLoad
{
[super viewDidLoad];
[self.view addSubview:[PlayerImageController addPlayerImage]];
}
- (void)somethingHappened
{
[PlayerImageController changePlayerImage];
}
并将我的方法放在我的PlayerImageController类中,如
+ (UIImageView *) addPlayerImage
{
heroPlayerImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"hero-still.png"]];
[heroPlayerImageView setFrame:CGRectMake(151, 200, 17, 23)];
return heroPlayerImageView;
}
+ (void) changePlayerImage
{
//change image
}
谢谢!
答案 0 :(得分:1)
我认为在你的情况下你应该使用Delegate模式。 声明:
@protocol PlayerImageUpdater
- createPlayerImage;
- changePlayerImage;
@end
然后添加:
@interface PlayerImageController <PlayerImageUpdater>
然后添加到MainViewController ivar和属性,如:
@property (...) id<PlayerImageUpdater> playerDelegate;
将此委托设置为:mainViewController.playerDelegate = playerImageControllerInstance;
并在代码中使用:
[playerDelegate createPlayerImage];
[playerDelegate changePlayerImage];
答案 1 :(得分:1)
一方面,我不建议使用类方法而是实例方法。这样,您可以根据需要实现任意数量的实例,并保留对实例的引用以进行更新。
另一方面,如果UIImageView
是您班级的重要属性,我建议您将其实现为UIView
子类(如果不是,则可以将其作为{NSObject
1}}子类,并获取其UIImageView属性。)
查看以下代码:
PlayerImageController.h:
@interface PlayerImageController : UIView{
UIImageView *_heroPlayerImageView;
}
-(void) changePlayerImage;
PlayerImageController.m:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_heroPlayerImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"hero-still.png"]];
// x = 0 and y = 0 because its relative to its parent view, the object itself.
[_heroPlayerImageView setFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
[self addSubview:_heroPlayerImageView];
}
return self;
}
MainViewController.h:
#import "PlayerImageController.h"
@interface MainViewController : UIViewController{
PlayerImageController *_player;
}
MainViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
_player = [[PlayerImageController alloc] initWithFrame:CGRect(151, 200, 17, 23)];
[self.view addSubview:_player];
}
- (void)somethingHappened
{
[_player changePlayerImage];
}
我希望它可以帮到你(我实际上没有尝试过上面的代码,它可能会有一些语法错误)。
如果您不使用ARC,请记住保留并释放变量!祝你好运!