Skip to content

Instantly share code, notes, and snippets.

@indyfromoz
Last active January 1, 2016 08:19
Show Gist options
  • Save indyfromoz/8117766 to your computer and use it in GitHub Desktop.
Save indyfromoz/8117766 to your computer and use it in GitHub Desktop.
Update background image of a view based on device orientation
/*
Add this in a view
*/
- (void)viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
// Update the background image if the device is an iPad and its orientation changed
- (void)orientationChanged:(NSNotification *)notification {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) {
UIImage* img = [UIImage imageNamed:@"background-landscape~ipad.png"];
[self.ipadBackgroundImageView setImage:img];
self.ipadBackgroundImageView.transform = CGAffineTransformMakeRotation(M_PI/2);
NSLog(@"Device orientation changed to Landscape");
} else if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)) {
[self.ipadBackgroundImageView setImage:[UIImage imageNamed:@"background-portrait~ipad.png"]];
self.ipadBackgroundImageView.transform = CGAffineTransformMakeRotation(0.0);
NSLog(@"Device orientation changed to Portrait");
}
}
}
- (void)viewDidDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}
/*
In application delegate's didFinishLaunchingWithOptions, add this -
// Start generating device orientation change notifications
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment