Reputation: 3971
I have to make som changes to a iPhone app...
How can i change the background on a UIViewController on load (viewDidLoad) .. I have to show a .png from a URL .. Is that posible?
I have tried:
NSURL *url = [NSURL URLWithString:@"http://url_to_my_project/xmas-bg-test.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
this is from my : "- (void)viewDidLoad" method .. Nothing happend when I start my app.. no errors ether.
I have also tried from my .. viewDidAppear
Upvotes: 0
Views: 224
Reputation: 130222
The other answers are correct for saying that you should be using an image view to display the image. However, you should consider making a request for the image. This way, if the request fails you can handle it by displaying a different image or what ever you want. Here's a rough example.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://url_to_my_project/xmas-bg-test.png"] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:5.0];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (response && !error) {
UIImage *image = [UIImage imageWithData:data];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
[imageView setImage:image];
[self.view addSubview:imageView];
}
}];
Upvotes: 0
Reputation: 5133
You have to create UIImageView
as a background image. Remove self.view.backgroundColor = ...
line and add this:
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = self.view.frame;
[self.view addSubview:imageView];
[self.view sendSubviewToBack:imageView];
in viewDidLoad:
method.
Upvotes: 1
Reputation: 40221
That's not how you add a background to a view controller. Add a new UIImageView
ivar to your view controller subclass and use that.
- (void)viewDidLoad {
...
imageView.image = [UIImage imageWithData:data];
}
You have to make sure you create this image view properly. Either by adding an image view in Interface Builder and linking it to your imageView
ivar, or by creating it yourself in awakeFromNib
or loadView
.
Upvotes: 1