2013-11-03 33 views
1

我是新的Mac应用程序,并且正在编写一个简单的应用程序,它具有应用程序不同部分的通用布局。它基本上是一个带有一个或两个按钮(标题不断变化)的图像。自定义NSView与插座

所以我想创造一个CustomNSView有一个形象好和两个圆形按钮,一个新的笔头文件,并在一个单独的类文件(MyCustomView,这是一个NSView的子类),将在initWithframe方法加载此笔尖。所以现在,当我拖放一个自定义视图并将其类设置为MyCustomView时,我无需任何附加代码即可立即获取图像和两个按钮。但是现在我该如何控制其他视图控制器中的这些按钮(插座/动作)?每个地方都会使用相同的视图,因此我无法将视图控制器中的文件所有者设置为笔尖?

这样做是否正确?有没有什么办法来创建一个自定义视图,委托所有按钮操作,其中包含的视图控制器?

+0

希望我可以在这个问题上设置赏金。我真的想知道它是否可能。 –

回答

0

您可以编写自定义代表。虽然使用的是,你可以发送消息从一个对象到另一个

+1

我不明白这是如何回答这个问题的。 – trojanfoe

0

以下是我将如何做到这一点。我不会创建一个CustomNSView,我会创建一个CustomViewController(包含它的xib文件)。在那个CustomViewController上,我会设计两个按钮并像这样设置CustomViewController.h。

@property (nonatomic, weak) id delegate; // Create a delegate to send call back actions 
-(IBAction)buttonOneFromCustomVCClicked:(id)sender; 
-(IBAction)buttonTwoFromCustomVCClicked:(id)sender; 

CustomViewController.m像这样。

-(void)buttonOneFromCustomVCClicked:(id)sender { 
    if ([self.delegate respondsToSelector:@selector(buttonOneFromCustomVCClicked:)]) { 
     [self.delegate buttonOneFromCustomVCClicked:sender]; 
    } 
} 

-(void)buttonTwoFromCustomVCClicked:(id)sender { 
    if ([self.delegate respondsToSelector:@selector(buttonTwoFromCustomVCClicked:)]) { 
    [self.delegate buttonTwoFromCustomVCClicked:sender]; 
    } 
} 

在你customViewController的界面生成器,这两个按钮的SentAction事件连接起来,这两种方法(它们应显示在file's owner)。

然后在您想要加载通用自定义视图的其他类中,像这样实例化通用视图控制器。

#import "customViewController.h" 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    customViewController *newCustomViewController = [[ViewController alloc] initWithNibName:@"customViewController" bundle:nil]; 
    [newCustomViewController setDelegate:self]; 

    self.backGroundView = [newCustomViewController view]; // Assuming **backGroundView** is an image view on your background that will display the newly instantiated view 
} 

-(void)buttonOneFromCustomVCClicked:(id)sender { 
    // Code for when button one is clicked 
} 

-(void)buttonTwoFromCustomVCClicked:(id)sender { 
    // Code for when button two is clicked 
}