swa*_*ner 7 macos interface-builder
我想在Interface-Builder中设置一个自定义的NSView,但我不认为它适用于OSX.
在我的ViewController的.xib中,我添加了一个自定义视图并将Class设置为MyCustomView.我创建了MyCustomView.h,MyCustomView.m和MyCustomView.xib.
在MyCustomView.xib中,我也将Class设置为MyCustomView.在MyCustomView.m中,- (void)awakeFromNib被调用,但是- (id)initWithCoder:(NSCoder *)aDecoder并- (id) awakeAfterUsingCoder:(NSCoder*)aDecoder没有.
我想要实现的是,在我的ViewController中,我添加的视图被"填充"了我在MyCustomView.xib中设置的视图.最好的方法是什么?
编辑:我认为我不够清楚......
我的ViewController包含一个名为MyCustomView的自定义视图.

此视图应为MyCustomView类型,其中
MyCustomView.h MyCustomView.m MyCustomView.xib
存在.我已经将MyCustomView.xib的文件所有者设置为MyCustomView,我已经将ViewController中的CustomView设置为MyCustomView - 但它不起作用.
如果我这样做的话
- (void)awakeFromNib {
NSString* nibName = NSStringFromClass([self class]);
NSArray* topLevelObjects;
[[NSBundle mainBundle] loadNibNamed:nibName
owner:nil
topLevelObjects:&topLevelObjects];
NSView* view = topLevelObjects[0];
[view setFrame:[self bounds]];
[self addSubview:view];
}
Run Code Online (Sandbox Code Playgroud)
我只获得了NSView类型的视图,而不是MyCustomView ......有没有简单的方法告诉ViewController.xib它是一个MyCustomView?
编辑2:我上传了一个简单的项目
在https://dl.dropboxusercontent.com/u/119600/Testproject.zip中,您可以找到一个带有MyCustomView的简单项目(不在ViewController中,但在window.xib中) - 但是它没有显示出的按钮MyCustomView.xib.我想要实现这一目标 - 最简单,最好的方法是什么?
fou*_*dry 18
编辑 - 道歉,我现有的答案没有考虑连接出口和行动的需要.这种方式应该这样做......
给出文件......
MyCustomView.h
MyCustomView.m
MyCustomView.xib
Run Code Online (Sandbox Code Playgroud)
在MyCustomView.h中
为您的界面元素声明IBOutlets.您至少需要一个,以指向xib文件中的顶级视图
@property (nonatomic, strong) IBOutlet NSView *view;
在MyCustomView.xib中
NSView类.view插座.在MyCustomView.m中:
- (id)initWithFrame:(NSRect)frame
{
NSString* nibName = NSStringFromClass([self class]);
self = [super initWithFrame:frame];
if (self) {
if ([[NSBundle mainBundle] loadNibNamed:nibName
owner:self
topLevelObjects:nil]) {
[self.view setFrame:[self bounds]];
[self addSubview:self.view];
[self.myCustomButton setTitle:@"test success"];
}
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
在窗口的xib文件中,添加自定义NSView并将其类更改为MyCustomView.
在10.8之前的OSX中,该方法loadNibNamed是一个类方法 - 如果您需要向后兼容性,请使用它,但现在不推荐使用它:
[NSBundle loadNibNamed:@"NibView" owner:self]
Run Code Online (Sandbox Code Playgroud)
请注意,MyCustomView.xib的视图不是 MyCustomView的视图,而是视图的唯一子视图(这类似于tableViewCell拥有单个contentView的方式).
在您发布的项目示例中,您需要进行以下更改:
在MyCustomView.h中
.添加NSView属性
在MyCustomView.xib中:
.将顶级视图从MyCustomView自定义类更改为NSView(默认值)
.将文件所有者设置为MyCustomView.
.从文件的所有者连接IBOutlets view和myCustomButton接口视图和按钮
.用于测试使视图更小并将按钮向上推到右上方(您将不会在窗口中看到它,因为它在这里)
在MyCustomView.m :
. 用initWithFrame这里的方法替换所有实现代码