我已经修改了苹果公司的Scrolling示例,以获取从
有人能给我一些帮助,告诉我如何最好地实现这个功能吗?
以下是从
以下是在滚动视图中布置图像的代码:
CoreData
对象引用的文件创建的一系列图像。我可以很好地添加这些图片,但我还想在每个图像上以编程方式添加一个UIButton
。图片的数量取决于CoreData
对象的数量,因此我不能使用IB。有人能给我一些帮助,告诉我如何最好地实现这个功能吗?
以下是从
CoreData
存储库中获取图像的代码:NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
Sentence *testSentence = [[managedObjectContext executeFetchRequest:request error:&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
以下是在滚动视图中布置图像的代码:
- (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]] && view.tag > 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)];
}
aButton.frame = imageView.bounds
,虽然在这种情况下我认为这并不重要。你可能还需要设置imageView.userInteractionEnabled=YES
(默认情况下 UIImageView 的值为 NO,如果我没记错的话)。 - tc.