2017-07-17 3 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

デリゲートメソッド – Paulw11

答えて

0

ViewController.m で、イベントを受信することができますあなたはどこ

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

model.m INとのViewControllerまたは

@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

を呼び出す 'Ball'クラスに' setColor'メソッドが必要です。最後に(おそらく:D)を使って委譲を理解しました。しかし、まだ1つの質問があります。私は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 

はまた前にデリゲートを設定することを忘れないでくださいを。

関連する問題