调整从xib创建的UIView的大小?

Ste*_*all 4 xib uiview ios autolayout

我正在从xib创建一个UIView,最终渲染成UIImage.

UIView本身具有内部约束,在IB中具有足够大的帧大小时可以正常工作.但是,我需要将宽度调整为某些特定内容,我无法弄清楚如何在从xib加载后设置UIView的宽度.

[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil][0];

要渲染视图,我这样做:

UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

然而,无论我设置的是什么,UIView的大小都与IB中的初始大小相同.如何设置UIView的大小,以便它会导致内部约束调整大小并正确呈现?

val*_*fer 6

尝试设置视图的所需帧,然后在其上调用layoutIfNeeded:

UIView *view = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil][0];
CGRect finalFrame = CGRectMake(0, 0, 90, 90);
view.frame = finalFrame;
[view layoutIfNeeded];

UIGraphicsBeginImageContextWithOptions(finalFrame.size, NO, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)