2011-11-25 98 views
0

我試圖在兩個類中調用一個IBAction方法,每當我在界面構建器中創建的按鈕被單擊時調用它。我真正想要發生的是每當單擊按鈕時出現NSRect,但是按鈕和我希望NSRect出現的位置處於單獨的視圖中,因此該按鈕位於視圖A中,且矩形的目標位於查看B.我曾嘗試用NSNotificationCenter做這件事,但它沒有奏效。在兩個類中調用IBAction方法

回答

2

您錯過了CMVC。可可使用模型 - 查看-控制器設計模式,你似乎缺少一個控制器。

您應該創建一個控制器類(可能是NSWindowController的一個子類,以便它負責窗口),該類實現了一個操作方法,如-buttonPressed:連接到您的按鈕。控制器應該管理模型(在這種情況下,無論矩形代表什麼),以便當您按下按鈕時,模型會更新。然後控制器應該讓你的矩形視圖重繪自己。

應該設置您的矩形視圖,以便它實現數據源模式(請參閱NSTableView數據源實現的一個很好的示例),以便知道有多少個矩形以及在哪裏繪製矩形。如果將控制器設置爲視圖的數據源,則視圖不需要知道有關模型的任何信息。

你的矩形認爲應建立這樣的:

RectangleView.h: @protocol RectangleViewDataSource;

@interface RectangleView : NSView 
@property (weak) id <RectangleViewDataSource> dataSource; 
@end 

//this is the data source protocol that feeds the view 
@protocol RectangleViewDataSource <NSObject> 
- (NSUInteger)numberOfRectsInView:(RectangleView*)view; 
- (NSRect)rectangleView:(RectangleView*)view rectAtIndex:(NSUInteger)anIndex; 
@end 

RectangleView.m:

@implementation RectangleView 
@synthesize dataSource; 

- (void)drawRect:(NSRect)rect 
{ 
    //only draw if we have a data source 
    if([dataSource conformsToProtocol:@protocol(RectangleViewDataSource)]) 
    { 
     //get the number of rects from the controller 
     NSUInteger numRects = [dataSource numberOfRectsInView:self]; 
     for(NSUInteger i = 0; i < numRects; i++) 
     { 
      NSRect currentRect = [dataSource rectangleView:self rectAtIndex:i]; 
      //draw the rect 
      NSFrameRect(currentRect); 
     } 
    } 
} 
@end 

你會指定你的控制器作爲視圖的數據源,並使其實現RectangleViewDataSource協議的方法。

控制器會是這個樣子:

YourController.h

#import "RectangleView.h" 

@interface YourController : NSWindowController <RectangleViewDataSource> 
@property (strong) NSMutableArray* rects; 
@property (strong) IBOutlet RectangleView *rectView; 

- (IBAction)buttonPressed:(id)sender; 

@end 

YourController.m

@implementation YourController 
@synthesize rects; 
@synthesize rectView; 

- (id)init 
{ 
    self = [super init]; 
    if (self) 
    { 
     rects = [[NSMutableArray alloc] init]; 
    } 
    return self; 
} 


- (void)awakeFromNib 
{ 
    //assign this controller as the view's data source 
    self.rectView.dataSource = self; 
} 

- (IBAction)buttonPressed:(id)sender 
{ 
    NSRect rect = NSMakeRect(0,0,100,100); //create rect here 
    [rects addObject:[NSValue valueWithRect:rect]]; 
    [self.rectView setNeedsDisplay:YES]; 
} 

//RectangleViewDataSource methods 
- (NSUInteger)numberOfRectsInView:(RectangleView*)view 
{ 
    return [rects count]; 
} 

- (NSRect)rectangleView:(RectangleView*)view rectAtIndex:(NSUInteger)anIndex 
{ 
    return [[rects objectAtIndex:anIndex] rectValue]; 
} 


@end 
+0

謝謝!它現在有效! –

+0

哦,別再介意它可以工作,但NSRect不會畫圖 –

+0

現在Xcode說屬性數據源不符合協議。你知道如何解決這個問題嗎? –

1

他們在單獨的窗口?如果它們不是,只需在ViewB中聲明一個IBAction並將它連接到ViewA中的按鈕即可。如果他們在不同的窗口,NSNotificationCenter的方式應該工作。您是否使用postNotificationName:addObserver:selector:name:object以及相同的通知名稱?

1

你想擁有一個控制器,通過rects知道視圖。將按鈕掛到控制器上。按下按鈕時,添加一個矩形。

相關問題