[英]Custom NSView with outlets
这是Mac应用程序的新手,并且正在编写一个简单的应用程序,该应用程序在应用程序的不同部分具有相同的布局。 它基本上是一幅在所有部分都带有一个或两个按钮(标题不断变化)的图像。
因此,我想到了在一个新的Nib文件和一个单独的类文件(MyCustomView,它是NSView的子类)中用一个图像孔和两个圆形按钮创建CustomNSView
方法,它将在initWithframe
方法中加载该Nib。 因此,现在每当我拖放自定义视图并将其类设置为MyCustomView
我都会立即获得Image和两个按钮,而无需任何其他代码。 但是现在我如何在其他View Controller中控制这些按钮(插座/动作)? 同一视图将在每个地方使用,因此我无法将nib中的文件所有者设置为视图控制器吗?
这样做对吗? 有什么方法可以创建一个自定义视图,该视图将所有按钮动作委派给其中包含的视图控制器吗?
您可以编写自定义委托。 尽管可以使用它将消息从一个对象发送到另一个对象
这就是我要做的。 我不会创建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
)。
然后在要加载通用自定义视图的otherClass中,实例化通用视图控制器,如下所示。
#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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.