问题
I have a UIView
defined in a .xib file. I need to set translatesAutoresizingMaskIntoConstraints = NO
. This means that the frame is not translated to constraints so I need to set the size constraints by myself.
I have created a working category method for a UIView
:
-(NSArray*)setSizeConstraints:(CGSize)size
{
NSLayoutConstraint* height = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:size.height];
NSLayoutConstraint* width = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:size.width];
[self addConstraint:height];
[self addConstraint:width];
return [NSArray arrayWithObjects:height, width, nil];
}
But I would like to set these constraints from the Xcode interface builder, but all my AutoLayout controls are greyed out:

Is there a way to do this in the interface builder?
回答1:
This actually is possible.
Simply put the view you'd like to constrain into another view, like the highlighted view here.
Then, add your desired constraints.
Finally, pull the view you just added constraints to out of its parent view. You can now add constraints to that view.
回答2:
As you've surely found out by now, it looks like there's currently no way to set Autolayout constraints at the main UIView
level from Interface Builder.
I had a similar problem here (Launch Screen XIB: Missing Width / Height Constraints (Xcode 6)), while working with the launch screen of my app.
The only workarounds I found, if you want to keep working with IB, are:
- Using a
UIViewController
and itsUIView
inside the XIB, instead of just aUIView
- Working only with Storyboards (and, once again,
UIViewController
)
However, I understand these approaches may not be ideal or "clean", especially if you simply have a subclass of UIView
and you want to draw its interface in a good old XIB.
来源:https://stackoverflow.com/questions/24527478/adding-constraint-to-the-main-view-in-a-xib