2012-01-24 94 views
0

控制的UIImageView子視圖我有兩個類:MainViewController和PlayerImageController(NSObject的)添加並從另一個類

我將如何能夠從PlayerImageController我的UIImageView的子視圖添加到我的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 
} 

謝謝!

回答

1

我認爲你的情況你應該使用委託模式。 聲明:本

@protocol PlayerImageUpdater 
    - createPlayerImage; 
    - changePlayerImage; 
@end 

然後加:

@interface PlayerImageController <PlayerImageUpdater> 

然後添加到MainViewController伊娃和財產,如:

@property (...) id<PlayerImageUpdater> playerDelegate; 

集此委託,如:mainViewController.playerDelegate = playerImageControllerInstance;

,並在代碼中使用:

[playerDelegate createPlayerImage]; 
[playerDelegate changePlayerImage]; 
1

一方面,我不會推薦使用類方法,但實例方法。這樣,您可以根據需要實現儘可能多的類實例,並保留對實例的引用來更新它們。

在另一方面,如果UIImageView是你們班的重要因素,我建議你實現它作爲一個UIView子類(如果不是的話,你可以做到這一點作爲一個NSObject子類爲好,並得到其的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; 
} 

的MainView Controller.m:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    _player = [[PlayerImageController alloc] initWithFrame:CGRect(151, 200, 17, 23)]; 
    [self.view addSubview:_player]; 
} 

- (void)somethingHappened 
{ 
    [_player changePlayerImage]; 
} 

我希望它可以幫助你(我沒有真正嘗試過上面的代碼,它可能有一些語法錯誤)。

如果您不使用ARC,請記住保留並釋放您的變量!祝你好運!

相關問題