I have a UITableViewController with a list of image names. When a name is clicked, the URL of the image is set in the ImageViewController and then the the UITableViewController segues to the ImageViewController that contains a UIImageView (connected with an outlet). In the ImageViewController‘s viewDidLoad I set the UIImageView to the image from the URL but when I run it on the simulator, only a black screen appears where the image should be.
A little visual description of the segue (where -> means segue):
ImageListTableViewController–> ImageViewController(hasUIImageView)
ImageListTableViewController.m
// The delegate here is the ImageViewController
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"Show Image"]) {
[self setDelegate:segue.destinationViewController];
}
}
// getting URL and calling the protocol method (in ImageViewController) which sets
// the image as an @property
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *imageDict = [self.imageArray objectAtIndex:indexPath.row];
NSURL *imageURL = [FlickrFetcher urlForPhoto:imageDict format:FlickrPhotoFormatLarge];
NSLog([imageURL description]);
[self.delegate imageListTableViewController:self withURL:imageURL];
}
ImageViewController.m
#import "ImageViewController.h"
@implementation ImageViewController
@synthesize image = _image;
@synthesize imageView = _imageView;
- (void)imageListTableViewController:(ImageListTableViewController *)sender
withURL:(NSURL *)imageURL;
{
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
self.image = [UIImage imageWithData:imageData];
}
#pragma mark - View lifecycle
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
// nothing
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
[self.imageView setImage:self.image];
}
- (void)viewDidUnload
{
[self setImageView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
@end
Any ideas on what’s going on?
Thanks!
Not really the right way to use a delegate. Try this:
In
ImageViewController.h:In
ImageViewController.mRemove imageListTableViewController
Change
viewDidLoad:Add to
viewDidUnload:Then in your
ImageListTableViewController.m:Change
prepareForSegue:Change your
didSelectRowAtIndexPath:Make sure you have connected that Segue to the VC itself and not to the TableView. If you don’t that Segue will get fired before
didSelectRowAtIndexPathis fired. In this case, it won’t make a difference, but for real control – get in the habit of connecting to the VC and calling performSegue when needed.