Adding objects to an NSView

心不动则不痛 提交于 2019-12-10 22:39:15

问题


I have an NSView inside my project's window as seen in the picture below:

How do I add NSImageViews to the subview of this 'Custom View' so its displayed in there rather than directly in the main window of the application?


回答1:


Programmatically, you would access the view to which you want to add subviews, then call the -addSubView: method on it. You can access it either as an IBOutlet hooked in to interface builder, or access it by Identifier (set the Identifier string in the "identity" section in the interface builder inspector). Iterate through the subviews of the windowcontroller's view (your custom view would be one) and test the string value of "identifier"

Here's a simplified code snippet from a recent project for programmatically adding an extra "properties" box into a view that already has a box defined in the xib. I'm adding a new box view (propertiesBoxView) into an existing NSView (referenced by the IBOutlet-ed _detailsView) and positioning it relative to another sibling box (with its identifier set to "UI_DETAILSBOX"). An NSImageView should behave the same way as a box view:

_propsViewController = [[MySpecialViewController alloc] initWithThings:...];
/* snip */

NSView *propertiesBoxView = [_propsViewController view];
NSView *detailsBox = nil;
// find the details box
for (NSView *sibling in [_detailsView subviews]) {
  if ([[sibling identifier] isEqualToString:@"UI_DETAILSBOX"]) {
    detailsBox = sibling;
    break;
  }
}
if (detailsBox == nil) {
  return;
}

[_detailsView addSubview:propertiesBoxView];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(propertiesBoxView, detailsBox);
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[detailsBox]-9-[propertiesBoxView]-(>=9)-|"
                                                             options:0
                                                             metrics:nil
                                                               views:viewsDictionary];
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-9-[propertiesBoxView]-(>=9)-|"
                                                             options:0
                                                             metrics:nil
                                                               views:viewsDictionary];
[_detailsView addConstraints:verticalConstraints];
[_detailsView addConstraints:horizontalConstraints];



回答2:


Drag and drop NSImageViews on NSView that will add NSImageViews to NSView as subviews in Interface builder



来源:https://stackoverflow.com/questions/12265308/adding-objects-to-an-nsview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!