2013-06-03 13 views
0

我控制器從UIView類的信息發送給UIViewController的

#import <UIKit/UIKit.h> 
#import "ViewBoard.h" 

@interface BallsViewController : UIViewController 
@property (weak, nonatomic) IBOutlet UILabel *InfoLabel; 
@property (weak, nonatomic) IBOutlet UIButton *nextBallButton; 
@property (weak, nonatomic) IBOutlet UILabel *PointLabel; 
@property (weak, nonatomic) IBOutlet ViewBoard *viewBoard; 

- (IBAction)NewGame:(id)sender; 

@end 





#import "BallsViewController.h" 
#import "Field.h" 
@interface BallsViewController() 
@end 

@implementation BallsViewController 
@synthesize viewBoard; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [self.viewBoard Draw:@"Fields"]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (IBAction)NewGame:(id)sender { 
    self.viewBoard.canDrawBall = true; 
    [self.viewBoard Draw:@"Fields"]; 

    } 
@end 

而且UIView

@interface ViewBoard : UIView 

@end 

@implementation ViewBoard 
-(void)sendScoreToUI{ 
int score = 10; 
} 
@end 

我怎麼能發送約比分UI信息,並有將其設置爲標籤?我想UIView發送這個信息給控制器比控制器從UIView得到它。

+1

您可以通過直接調用某個方法從控制器與您的自定義視圖進行通信,因爲控制器具有該ViewBoard的實例。要創建從視圖到控制器的通信,最好的方法可能是使用協議。該視圖可以有一個代表響應該協議(這將是控制器),並可以從中調用一些功能。這是回答你的問題嗎? –

回答

2

考慮MVC,模型 - 視圖 - 控制器。 視圖是ViewBoard。 控制器是BallsViewController,其中包含應用程序邏輯。 模型應該是分數。

所以你有3個選擇如何管理模型。請注意,在我的情況下,應用程序的邏輯總是在控制器內部,所以管理遊戲和得分的控制器,而不是用戶界面。

選擇-1:嚴格MVC

得分被建模爲一個獨立的對象。在這種情況下,你定義了一個「分數」類,你從控制器到模型發送比分更新,讓視圖監聽模型的變化:


@interface Score 
@property (nonatomic,assign) NSInteger points; 
@end 
@implementation Score 
@synthesize points; 
@end 

然後控制器實例化對象得分:


Score *myScore; 

更新它當一個得分事件發生:


[myScore setPoints:30]; 

最後,你可以使用志願讓ViewBoard爲偵聽myScore的「點」屬性的變化。因此,在myScore被初始化後,控制器內部:


[myScore addObserver:self.viewBoard forKeyPath:@"points" options:NSKeyValueOptionNew context:NULL]; 

注意:模型和視圖僅由KVO鏈接。因此,該視圖不會改變分數,並且該模型僅通過KVO過程纔會通知視圖。當控制器消失時,KVO鏈路斷開。

選擇-2:模型是控制器 在這種情況下,你只是一個新的屬性添加到您的控制器內:


@property (nonatomic,assign) NSInteger points; 

,每次更新您發送新值將比分視圖(更新自己)。您可以在點設置器中執行此操作:每次更新內部點屬性時,都會要求viewBoard自行更新。

 
[self setPoints:30];

-(void)setPoints:(NSInteger)newPoints { points = newPoints; [self.viewBoard updatePoints:points]; }

選擇-3:模型是視圖 這種方法是簡單的,但通常不建議裏面,因爲通常你不希望添加的控制器和視圖表示之間的強依賴性(這種情況因爲您的視圖需求可能會影響視圖控制器更新其邏輯的方式)。另外一個限制是,在視圖卸載事件中,您可能會失去分數。 在這種情況下,你點屬性添加到視圖:


@property (nonatomic,assign) NSInteger points; 

,並在您的視圖控制器,你可以通過這種方式改變點:


[self.viewBoards setPoints:30]; 

最後您的視圖「設置點:」 setter方法包含一些「刷新」邏輯:


-(void)setPoints:(NSInteger)newPoints { 
    points = newPoints; 
    [self setNeedsLayout]; 
} 

-(void)layoutSubviews { 
    // here you update the subview 
    [self.pointsLabel setText:[NSString stringWithFormat:@"%d",self.points]]; 
} 



+0

非常好的答案! +1 –