Search code examples
objective-cswiftxcodexibnslayoutconstraint

How do I translate swift NSLayoutConstraint activateConstraints to objective c?


I have successfully made a project in swift where I press buttons in my viewController to load other viewControllers or xib files into a container. Just to give you an idea:

enter image description here

It works great, but I'm having a difficult time translating it to objective-c which is where the code is actually needed. This is what the swift code looks like when pressing a button:

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)
        ])

Now, I would like all that code to be in objective-c instead. In objective-c I have done the first part, which I assume is correct:

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

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

But I'm having problem with the last part, NSLayoutConstraint activateConstraints

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

The compiler says that property lead not found on object of type UIBib and same on the code just below. I have tried a variation of these, but don't get it right. How do I set trailing, leading, bottom and top constraints on my xib? Do I need to add #import SecondView.xib" in the.h` file? by the way?


Solution

  • You can try

    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]
    ]];