我修改了Apple的Scrolling示例以抓取从CoreData
对象中引用的文件创建的一系列图像。我可以添加图像很好,但我也想以编程方式为每个图像添加一个UIButton
。图像的数量取决于CoreData
对象的数量,所以我不能使用IB。以编程方式将UIButtons和UIImage添加到UIScrollview中
任何人都可以给我一些帮助,我将如何最好地实现这一点?
下面是争夺从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)];
}
感谢您的回答。是的工作 - 但我不能点击按钮(它坚定地忽略我的点击/水龙头 - 是的,我已经改变了行动),我想要一个不像imageView.frame大小的按钮。有任何想法吗? – glenstorey 2010-11-21 03:23:31
你可能是指'aButton.frame = imageView.bounds',虽然在这种情况下我认为它不重要。您可能还必须设置imageView.userInteractionEnabled = YES(对于UIImageView,IIRC,默认值为NO)。 – 2010-11-21 05:41:14
排序出按钮/图像大小谢谢 - 但我不能让它点击。我试过了: [aButton setUserInteractionEnabled:YES]; [aButton setEnabled:YES]; [aButton setAlpha:1]; 我似乎无法取得任何进展。有没有一种方法可以调试您点击的内容?任何使事情奏效的策略? – glenstorey 2010-11-23 07:20:50