UIView size generated from xib?

I am creating a UIView from xib for final rendering to UIImage.

UIView itself has internal constraints that work fine given the large enough frame size in IB. However, I need to change the width to specific content and I cannot figure out how to set the width of the UIView after loading from the xib.

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

To pretend I am doing this:

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

      

Regardless of what I set for the borders, the UIView is the same size as the initial size in IB. How can I set the size of the UIView such that it can resize the internal dimensions and display them correctly?

+3


source to share


1 answer


Try setting your desired view frame and then call 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();

      

+6


source







All Articles