Adrian
Adrian

Reputation: 16715

How to tell a UIView what CGRect it goes in on a UIViewController

I've found and configured a UIView that works perfectly for what I'm trying to do, however I'm having a tough time configuring the CGRect for it.

What I've got:

1) MyViewController.h/m

2) CustomUIView.h/m

In interface builder, I added a UIView object and configured the AutoLayout constraints. In identity inspector, I set Custom Class to CustomUIView. I added an IBOutlet to MyViewController.m.

@property (strong, nonatomic) IBOutlet CustomUIView *customUIView;

In MyViewController's viewDidLoad, I use these commands to add customUIView:

[self.customView drawCustomViewInView:self.customUIView];

In CustomUIView.m, drawCustomViewInView has the following line, which I'm having a b***h of a time with:

customViewWidth = [UIScreen mainScreen].bounds.size.width - (2 * STEPPER_MARK_HEIGHT_WIDTH);

Originally, the values for drawing CustomUIView were hard-coded, so I just made the UIView object the width of the screen and called it a day. That came back to bite me in the @$$ when I started testing different screen sizes.

How would I get CustomUIView to know about the rect I want it to draw in on MyViewController? I know this isn't that hard, but I can't ****ing figure it out. I've discovered [UIScreen mainScreen] won't get the job done for every screen size...I need to tell it the rect.

Upvotes: 0

Views: 99

Answers (1)

Adrian
Adrian

Reputation: 16715

Adding two lines to MyViewController's viewDidLoad got me squared away:

self.customUIView.translatesAutoResizingMaskIntoConstraints = YES;
[self.customUIView setFrame:self.customUIView.frame];

Those two lines enabled me to incorporate a custom UIView with its own drawing methods into a UIViewController via AutoLayout. Special thanks to Luan Nguyen for pointing me in the right direction.

A more in-depth discussion of this topic can be found in "How I Learned to Stop Worrying and Love AutoLayout".

Upvotes: 0

Related Questions