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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With