如何将 swift NSLayoutConstraint activateConstraints 转换为 Objective C?

Whi*_*per 3 xcode objective-c xib nslayoutconstraint swift

我已经成功地在 swift 中创建了一个项目,我按下按钮将其他或文件viewController加载到容器中。只是给你一个想法:viewControllersxib

在此输入图像描述

它工作得很好,但我很难将它翻译成objective-c实际需要代码的地方。这是swift按下按钮时代码的样子:

let sub3 = UINib(nibName: "thirdXib", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView

containerOutlet.addSubview(sub3)

NSLayoutConstraint.activate([
    sub3.leadingAnchor.constraint(equalTo: containerOutlet.leadingAnchor),
    sub3.trailingAnchor.constraint(equalTo: containerOutlet.trailingAnchor),
    sub3.topAnchor.constraint(equalTo: containerOutlet.topAnchor),
    sub3.bottomAnchor.constraint(equalTo: containerOutlet.bottomAnchor)
        ])
Run Code Online (Sandbox Code Playgroud)

现在,我希望将所有代码都放入objective-c其中。我已经objective-c完成了第一部分,我认为这是正确的:

UINib *nib = [UINib nibWithNibName:@"SecondView" bundle:nil];
[nib instantiateWithOwner:self options:nil];

[containerOutlet addSubview:((UIView*)nib)];
Run Code Online (Sandbox Code Playgroud)

但我对最后一部分有问题NSLayoutConstraint activateConstraints

[NSLayoutConstraint activateConstraints:@[
        [nib.lead],
        [nib.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        ]
 ];
Run Code Online (Sandbox Code Playgroud)

编译器是这样说的property lead not found on object of type UIBib,下面的代码也是如此。我尝试过这些的变体,但没有得到正确的结果。如何在我的 xib 上设置尾随、前导、底部和顶部约束?我需要添加#import SecondView.xib" in the.h` 文件吗?顺便一提?

Sh_*_*han 7

你可以试试

UINib *nib = [UINib nibWithNibName:@"SecondView" bundle:nil]; 
UIView *sub3 = [nib instantiateWithOwner:self options:nil][0]; 
[containerOutlet addSubview:sub3];


[NSLayoutConstraint activateConstraints:@[
   [sub3.leadingAnchor constraintEqualToAnchor:scontainerOutlet.leadingAnchor],
   [sub3.trailingAnchor constraintEqualToAnchor:containerOutlet.trailingAnchor],
   [sub3.topAnchor constraintEqualToAnchor:containerOutlet.topAnchor],
   [sub3.bottomAnchor constraintEqualToAnchor:containerOutlet.bottomAnchor]
]];
Run Code Online (Sandbox Code Playgroud)