I have an iPhone app made up of a single UIWebView that displays a website. I have set a background image to the UIWebView after it finishes loading within my ViewController.m
file, as shown here:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
// Set UIWebView Background Image
self->webView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ui-background-portrait.png"]];
}
This is fine when the device is in Portrait orientation, but I would like to change the background image if the user switches the device orientation to landscape, and back to portrait if they switch again, etc.
I wrote the code below, but I'm not sure where to put it (as it needs to change the background image whenever they switch orientations; not just one time):
- (void)webViewDidFinishLoad:(UIWebView *)webView {
// Set UIWebView Background Image
if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
{
// code for Portrait orientation
self->webView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ui-background-portrait.png"]];
}
if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
{
// code for landscape orientation
self->webView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ui-background-landscape.png"]];
}
}
How can I accomplish this? And if you could give me code and indicate where to put it, that would be such a great help :)
Override one of these methods in your view controller and put your code there.
– willRotateToInterfaceOrientation:duration:
– willAnimateRotationToInterfaceOrientation:duration:
– didRotateFromInterfaceOrientation:
Put this code in your ViewController.m
- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation) fromInterfaceOrientation
{
// Set UIWebView Background Image
if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
{
// code for Portrait orientation
self->webView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ui-background-portrait.png"]];
}
if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
{
// code for landscape orientation
self->webView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ui-background-landscape.png"]];
}
}