自动调整从xib文件加载的视图

时间:2014-05-14 07:56:56

标签: ios iphone objective-c interface-builder xib

我的项目有以下Xib文件: XIB file

我试图在提示视图中添加一些新约束(超级视图的底部,顶部,左侧和右侧空间),但是如图所示,它不可能从界面构建器中找到。怎么做?

对应功能:

+ (instancetype)presentInViewController:(UIViewController *)viewController withDefaultsKey:(NSString *)defaultsKey {
    ELHintViewOwner *owner = [ELHintViewOwner new];
    NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:owner options:nil];
    //hintViewOwner.decoupledView.delegateViewController = viewController
    ELHintView *hintView = [bundle firstObject];
    hintView.frame = viewController.view.bounds;
    hintView.titleLabel.text = @"";
    hintView.defaultsKey = defaultsKey;
    hintView.tapAnywhereLabel.text = NSLocalizedString(@"Tap anywhere to continue", nil);
    hintView.showLabel.text = NSLocalizedString(@"Don't show this message again", nil);
    hintView.imageView.hidden = YES;
    hintView.showSwitch.on = ![[[NSUserDefaults standardUserDefaults] valueForKey:defaultsKey]  boolValue];

    if ([hintView shouldShow])
        [viewController.view addSubview:owner.decoupledView];
    return hintView;
}

1 个答案:

答案 0 :(得分:1)

如果要将superview添加到其他视图中,则必须在代码中添加自动布局约束。

+ (instancetype)presentInViewController:(UIViewController *)viewController withDefaultsKey:(NSString *)defaultsKey {
    ELHintViewOwner *owner = [ELHintViewOwner new];
    NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:owner options:nil];
    //hintViewOwner.decoupledView.delegateViewController = viewController
    ELHintView *hintView = [bundle firstObject];
    hintView.frame = viewController.view.bounds;
    hintView.titleLabel.text = @"";
    hintView.defaultsKey = defaultsKey;
    hintView.tapAnywhereLabel.text = NSLocalizedString(@"Tap anywhere to continue", nil);
    hintView.showLabel.text = NSLocalizedString(@"Don't show this message again", nil);
    hintView.imageView.hidden = YES;
    hintView.showSwitch.on = ![[[NSUserDefaults standardUserDefaults] valueForKey:defaultsKey]  boolValue];

    if ([hintView shouldShow]){
        [viewController.view addSubview:owner.decoupledView];
          hintView.translatesAutoresizingMaskIntoConstraints = NO;
          NSArray *constraintsX = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[hintView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(hintView)];
          NSArray *constraintsY = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[hintView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(hintView)];
          [viewController.view addConstraints:constraintsX];
          [viewController.view addConstraints:constraintsY];
     }
    return hintView;
}