我如何将快速的NSLayoutConstraint activateConstraints转换为目标c?

问题描述 投票:0回答:1

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

enter image description here

效果很好,但是我很难将其转换为实际需要代码的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)
        ])

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

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

[containerOutlet addSubview:((UIView*)nib)];

但是我在最后一部分NSLayoutConstraint activateConstraints上遇到问题

[NSLayoutConstraint activateConstraints:@[
        [nib.lead],
        [nib.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        ]
 ];

编译器说property lead not found on object of type UIBib与下面的代码相同。我尝试了这些方法的一种变体,但是做得不好。如何在xib上设置尾随约束,前导约束,最低约束和最高约束?我需要添加#import SecondView.xib" in the .h`文件吗?顺便问一下?

objective-c swift xcode xib nslayoutconstraint
1个回答
0
投票

您可以尝试

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]
]];
© www.soinside.com 2019 - 2024. All rights reserved.