I’ve achieved the point of headdesk, trying to dynamically create UIImageView in iOS 4.2.
This is the code that is causing me trouble:
1) The setup
UIImageView *iview = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 95, 149)];
iview.tag = 200; // see note 1
iview.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self.view addSubview:iview];
[iview release];
I’ve tried with both releasing and not releasing iview.
2) The payoff
NSString *img = ...[see note 2];
NSLog(@"Filename: %@", img);
UIImageView *pIV = (UIImageView *)[self.view viewWithTag:200];
if (pIV == nil) {
abort();
}
UIImage *pI = [UIImage imageWithContentsOfFile:img];
if (pI == nil) {
abort();
}
[pIV setImage:pI];
This is expanded to show what I’m looking at, since the terse version wasn’t working for me.
Note 1: Most of the above hardcoded values (200, the frame bounds, etc) are either #defines or computed in the forloop that the iview alloc code is within. Left out for brevity, but let me know if you think it’s relevent.
Note 2: This is just a message that returns the filepath after looking in NSBundle etc. The NSLog output is
2011-01-30 22:09:54.767 ribbit[13529:207] Filename: /Users/rip/Library/Application Support/iPhone Simulator/4.2/Applications/C421AA9F-45BB-41AB-8CB0-1540FABB56D3/ribbit.app/cardfront_a7.png
The .png does exist, and both the sentinels aren’t nil (so neither abort() happens).
I’m convinced that it’s just something basic.
Things I’ve tried:
1) Used IB to generate the UIImageView. When it was wired up correctly, I could see the frame, and the image that was given as the default in IB showed. I still could not, however, alter the image, which is why I moved to dynamically creating them…thought it would be simpler. Eh.
2) Tried using instance variables for the various iviews, but that was unwieldy (there are ten of these UIImageView being generated) and they didn’t work either.
Because all three attempts failed with the same behavior (runs fine, just can’t see the images), I’m assuming that it is just some silly little thing.
I welcome any suggestions you might have.
The issue appeared to be with the setImage (there wasn’t one) and opaque=YES.
I was pre-creating the UIImageViews, and then loading them with an image lazily, as needed, which is why the setImage wasn’t in the above code examples. Now I do, and it seems to be working:
Once I’d added those, the cards appeared. It may be that the problem was not /not/ being loaded or displayed, rather it was one of visibility.
Anyway, fuggedaboutit.