我修改了Apple的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
这是在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)];
}
答案 0 :(得分:1)
不确定我理解你的问题。你不能这样做吗?
...
imageView.frame = rect;
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
aButton.frame = imageView.frame;
[aButton addTarget:self action:@selector(whatever:) forControlEvents:UIControlEventTouchUpInside];
[imageView addSubview:aButton];
答案 1 :(得分:1)
我在创建图库时遇到了同样的问题,我添加到每个缩略图的按钮都不会响应TouchUpInside事件。
我能够通过创建一个自定义UIView子类来保持每个单独的图像并在该子类中实现touchesBegan:withEvent:和touchesEnded:withEvent:来实现它。
请参阅UIScrollView programming guide了解示例代码。
如果您不允许在UIScrollView上进行缩放,则可以通过假设每个触摸结束都是单个触摸事件来简化代码。