How to detect rotation for a programatically generated UIView

ios, objective-c, rotation, uiview

Solution

I think you have two options:

- You put the view in a custom `UIViewController` and override the `shouldAutorotateToInterfaceOrientation:` method to return YES for all the orientations you want to support. The view controller will automatically rotate and resize the content (your view). You just have to make sure to have the correct autoresizeMask (or constrains, if you're using autolayout).

- You directly observe changes to the devices orientation with the accelerometer. Then you can adjust your view when needed.

It's really the first approach you should choose if you can.

Problem

I have a `UIView` that's programmatically being created: ``` - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; if (self) { self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5]; UIImageView* closeButton = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"modal_close.png"]]; closeButton.frame = CGRectMake(self.frame.size.width*.89, self.frame.size.height*.09, closeButton.frame.size.width, closeButton.frame.size.height); UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width*.89, self.frame.size.height*.09,20, 20)]; [button addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside]; UIView* mainView = [[UIView alloc] initWithFrame:CGRectMake(self.frame.size.width*.1,self.frame.size.height*.1,self.frame.size.width*.8,self.frame.size.height*.8)]; mainView.backgroundColor = [UIColor whiteColor]; _displayMainView = mainView; [self addSubview:_displayMainView]; [self addSubview:closeButton]; [self addSubview:button]; mainView = nil; closeButton = nil; } return self; } ``` How can I detect rotation? This is to act as a modal on top of another existing view. This is an iPad only app, if that matters.

Original source

Related problems