简体   繁体   中英

UIImageView set image programmatically bug

I have a UIImageView in a storyboard, connected to the header of the subclassed UIViewController like this: @property (retain, nonatomic) IBOutlet UIImageView *displayPhoto;

In the .m of the UIViewController subclass, I try to set the image of the displayPhoto .

@synthesize displayPhoto;

-(void)awakeFromNib {
    UIImage *image = [UIImage imageNamed:@"dp.jpg"];

    [displayPhoto setImage:image];

    displayPhoto.layer.cornerRadius = displayPhoto.image.size.width/2;

    [self.view addSubview:displayPhoto];
}

but it does absolutely nothing. If I add one more line, adding another view of the image like so: [self.view addSubview:[[UIImageView alloc] initWithImage:image]]; , making my methodf

@synthesize displayPhoto;

-(void)awakeFromNib {
    UIImage *image = [UIImage imageNamed:@"dp.jpg"];

    [self.view addSubview:[[UIImageView alloc] initWithImage:image]];

    [displayPhoto setImage:image];

    displayPhoto.layer.cornerRadius = displayPhoto.image.size.width/2;

    [self.view addSubview:displayPhoto];
}

It suddenly starts working and adds to instances of the image to the view. One in the top left corner (from the line I added) and a second in the storyboard image location.

What's changing? How is adding that one line making my code work and is there any work around so I can make the image just show up as normal?

If you added the UIImage in your storyboard and connected the outlet correctly, there is no need to create a new image programmatically. Try this.

- (void) viewDidLoad {
     [super viewDidLoad];
     self.displayPhoto.image = [UIImage imageNamed:@"dp.jpg"];
}

检查imageview与情节提要的连接将解决您的问题。

用这个:

self.imgObj.image=[UIImage imageNamed:@"Your string"];

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