Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size a UIView created from a xib?

I'm creating a UIView from a xib to eventually render into a UIImage.

The UIView itself has internal constraints which work fine given a large enough frame size in IB. However, I need to size the width to some particular content, and I can't figure out how to set the width of the UIView after loading it from a xib.

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

To render the view, I do this:

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

No matter what I set the bounds to, however, the UIView is the same size as the initial size in IB. How can I set the size of the UIView such that it will cause internal constraints to resize and render correctly?

like image 832
Stefan Kendall Avatar asked Mar 19 '23 07:03

Stefan Kendall


1 Answers

Try setting the desired frame of the view and then calling layoutIfNeeded on it:

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();
like image 165
valfer Avatar answered Apr 01 '23 12:04

valfer