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

另外别忘了之前设定的委托。