Note that there are some explanatory texts on larger screens.

plurals
  1. POProgrammatically adding UIButtons and UIImages to a UIScrollview
    text
    copied!<p>I've modified Apple's <a href="http://developer.apple.com/library/ios/#samplecode/Scrolling/Introduction/Intro.html%23//apple_ref/doc/uid/DTS40008023-Intro-DontLinkElementID_2" rel="nofollow">Scrolling</a> example to grab a series of images created from files referenced in <code>CoreData</code> objects. I can add the images fine, but I also want to programmatically add a <code>UIButton</code> to each image. The number of images depends on the number of <code>CoreData</code> objects, so I can't use IB. </p> <p>Can anyone give me some help on how I would best implement this?</p> <p>Here's the code that grabs the images from the <code>CoreData</code> store:</p> <pre><code>NSUInteger i; for (i = 1; i &lt;= kNumImages; i++) { Sentence *testSentence = [[managedObjectContext executeFetchRequest:request error:&amp;error] objectAtIndex:i]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *imageName = [[paths objectAtIndex:0] stringByAppendingPathComponent:[testSentence image]]; NSLog(@"imageName: %@", imageName); UIImage *image = [[UIImage alloc] initWithContentsOfFile:imageName]; NSLog(@"image: %@", image); UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; NSLog(@"imageView: %@", imageView); [imageView setContentMode:UIViewContentModeScaleAspectFit]; [imageView setBackgroundColor:[UIColor blackColor]]; // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList" CGRect rect = imageView.frame; rect.size.height = kScrollObjHeight; rect.size.width = kScrollObjWidth; imageView.frame = rect; imageView.tag = i; // tag our images for later use when we place them in serial fashion [scrollView1 addSubview:imageView]; [image release]; [imageView release]; } [self layoutScrollImages]; // now place the photos in serial layout within the scrollview </code></pre> <p>And here's the code that lays the images out in the scrollview:</p> <pre><code>- (void)layoutScrollImages { UIImageView *view = nil; NSArray *subviews = [scrollView1 subviews]; // reposition all image subviews in a horizontal serial fashion CGFloat curXLoc = 0; for (view in subviews) { if ([view isKindOfClass:[UIImageView class]] &amp;&amp; view.tag &gt; 0) { CGRect frame = view.frame; frame.origin = CGPointMake(curXLoc, 0); view.frame = frame; curXLoc += (kScrollObjWidth); } } // set the content size so it can be scrollable [scrollView1 setContentSize:CGSizeMake((kNumImages * kScrollObjWidth), [scrollView1 bounds].size.height)]; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload