【ios】xib view autolayout

  最近在用xib做view的autolayout时,遇到了view的大小不能改变的问题,后来经过查资料,应该是没有配置view的约束问题。


autolayout - Reuse a uiview xib in storyboard - Stack Overflow

Works in Xcode 6.3.1

Create a new UIView named 'ReuseableView'

File > New > File > Source > Cocoa Touch Class > UIView

Create a matching xib file named 'ReuseableView'

File > New > File > User Interface > View

Set the file owner of the of the xib

select the xib

select file's owner

set custom class to 'ReusableView' in the Identity Inspector.

【ios】xib view autolayout_第1张图片

Note: Do not set the custom class of the view on the xib. Only the File Owner!

Make an outlet from the view in the ReuseableView.xib to your ReuseableView.h interface

Open Assistant Editor

Control + Drag from the view to your interface

【ios】xib view autolayout_第2张图片

Add initWithCoder implementation to load view and add as a subview.

- (id)initWithCoder:(NSCoder *)aDecoder{

self = [super initWithCoder:aDecoder];

if (self) {

// 1. load the interface

[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];

// 2. add as subview

[self addSubview:self.view];

// 3. allow for autolayout

[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];

// 4. add constraints to span entire view

[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];

[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];

}

return self;

}

【ios】xib view autolayout_第3张图片

Test your reuseable view in a storyboard

Open your storyboard

Add a view

Set that view's Custom Class

【ios】xib view autolayout_第4张图片

Run and observe!

【ios】xib view autolayout_第5张图片

你可能感兴趣的:(【ios】xib view autolayout)