在我的申请中,我有:
当应用加载时,我正在使用:
initWithNibName:nibName andReplaceView:(the custom view) resize:YES
替换自定义视图。我知道IB中的视图有一个选项placeholder
,但我不知道如何使用它,我的应用程序运行良好...
...除了加载的视图不继承替换视图的布局约束。
我该如何解决这个问题?
编辑抱歉,我忘了这个功能是我的...我很久以前在一个类别中写过它。这是代码:
- (id)initWithNibName:(NSString*)nibName andReplaceView:(NSView*)aView resize:(BOOL)resize
{
// 1. Loading the bundle
if (self = [self initWithNibName:nibName bundle:nil])
{
[self replaceView:aView resize:resize];
}
return self;
}
- (void)replaceView:(NSView*)aView resize:(BOOL)resize
{
if (resize)
{
NSRect insertionFrame = [aView frame];
[[self view] setFrame:insertionFrame];
}
else
{
NSRect insertionFrame = [aView frame];
insertionFrame.size.width = [[self view] frame].size.width;
insertionFrame.size.height = [[self view] frame].size.height;
[[self view] setFrame:insertionFrame];
}
NSView* supView = [aView superview];
[supView replaceSubview:aView with:[self view]];
}
答案 0 :(得分:1)
替换视图时,会删除附加到旧视图的所有布局约束。
就个人而言,我只是将新视图放在旧视图中。这是我用过的一些代码:
@implementation SJPlaceholderView
-(void) fillWithView:(NSView*)view {
NSParameterAssert(view);
view.frame = self.bounds;
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:view];
[self addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(view)]];
[self addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(view)]];
}
@end
这确保内部视图框架与外部视图框架完全匹配。外部视图上的所有布局约束仍然有效。
您还可以尝试遍历旧视图的所有约束,并将它们应用于新视图。大多数约束将在视图本身或超级视图上,但它们理论上可以在任何祖先视图上。