2017-07-17 62 views
0

我有具有顏色參數的模型類,以及也有UIColor的視圖類。使用委託如何在模型中更改我的視圖顏色。不能在使用委託的類之間進行通信

//Model.h 

@class Ball; 
@protocol BallDelegate <NSObject> 

-(void)ball:(Ball*)ball wasColorChanged; 

@end 

@interface Ball : NSObject 

@property UIColor* color; 
@property (weak) id <BallDelegate> delegate; 

@end 

現在,我該如何將值傳遞給我的視圖,如何調用它。

+1

您需要''Ball'類中的'setColor'方法來調用委託方法 – Paulw11

回答

0

model.m

[self.delegate wasColorChanged] // call this at the time of color change 

而且在視圖控制器或任何你可以接收事件,

ViewController.m

@interface ViewController()<BallDelegate> // Set ballDelegate in interface 

設置委託地方你創建你的對象

myBallModel.delegate = self; // set it where you created your object 

,並添加委託功能viewController.m

-(void)ball:(Ball*)ball wasColorChanged { 
    // You will receive the color change event here 
} 
+0

最後,我使用(可能是:D)理解委託。但還有一個問題。事情是我有一個BallManager單例類,只有那裏創建新的球。所以如果我在那裏設置新的球委託如何將其設置爲我的viewcontroller? :/ –

0

你可以做這樣的事情:

@protocol Ball 

- (void)setColor:(UIColor *)color { 
    // set new color 
    _color = color; 
    // tell the delegate about new color 
    if ([self.delegate respondsToSelector:@selector(ball: wasColorChanged:)]) { 
     [self.delegate ball:self wasColorChanged:color]; 
    } 
} 

@end 

另外別忘了之前設定的委託。