简体   繁体   中英

Set UIImageView in Another View Controller

I have a table view and when a row is selected it takes you to a detail page. The detail page has an image view on it. I am trying to set the image for the image view from the table view when the row is selected but when the row is selected and the detail view comes up, there is nothing but a white page.

Like this:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GRSBandDetailViewController *detail = [[GRSBandDetailViewController alloc]initWithNibName:@"GRSBandDetailViewController" bundle:nil];

    if (indexPath.row == 0)
    {
        [detail.bandImage setImage:[UIImage imageNamed:@"AbovetheUnderground.png"]];
        [self.navigationController pushViewController:detail animated:YES];
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

Here is the .h file for GRSBandDetailViewController:

@interface GRSBandDetailViewController : UIViewController
{
    IBOutlet UIImageView *bandImage;
}

@property (nonatomic, strong) UIImageView *bandImage;

@end

This is happening because the view is loaded lazily, during the first call to -[UIViewController view] . Thus detail.bandImage is nil when you try to set the image.

Provide the UIImage in the GRSBandDetailViewController initializer or via a property. Then set bandImage.image to the value of this property in viewDidLoad .

I fixed the problem by adding this to the detail view controller.

@property (nonatomic, strong) UIImage *passedImage;

@property (nonatomic, strong) NSString *titleString;

And viewDidLoad now has this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.title = titleString;
    bandImage.image = passedImage;
}

The didSelectRowAtIndexPath method from the table view looks like this:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GRSBandDetailViewController *detail = [[GRSBandDetailViewController alloc]initWithNibName:@"GRSBandDetailViewController" bundle:nil];

    if (indexPath.row == 0)
    {
        [self.navigationController pushViewController:detail animated:YES];
        detail.passedImage = [UIImage imageNamed:@"AbovetheUnderground.png"];
        detail.titleString = @"Above the Underground";
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM