【发布时间】:2010-08-23 01:27:10
【问题描述】:
我正在使用 UIScrollView 来保存大小为 80x80 的不同数量的图像,当用户点击一个时,我希望它启动到一个模态视图中,显示它全屏等。 我遇到的问题是检测滚动视图内图像的触摸。到目前为止,我已经尝试了两种方法,但每种方法都有问题。我同时发布了两种方式,但我只需要其中一种方式的答案。
我有一个图像数组并循环遍历它,这是我尝试为每个图像使用 UIImageView 的第一种方法:
for (i=0; i<[imageArray count]; i++) {
// get the image
UIImage *theImage = [imageArray objectAtIndex:i];
// figure out the size for scaled down version
float aspectRatio = maxImageHeight / theImage.size.height;
float thumbWidth = theImage.size.width * aspectRatio;
float thumbHeight = maxImageHeight;
lastX = lastX+10;
// Scale the image down
UIImage *thisImage = [theImage imageByScalingProportionallyToSize:CGSizeMake(thumbWidth, thumbHeight)];
// Create an 80x80 UIImageView to hold the image, positioned 10px from edge of the previous one
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(lastX, 10, 80, 80)];
image.clipsToBounds = YES;
image.contentMode = UIViewContentModeTopLeft;
image.image = thisImage;
image.userInteractionEnabled = YES;
// add to the scroller
[photoScroller addSubview:image];
// release
[image release];
// set variables ready for the next one
//lastWidth = thisImage.size.width;
lastWidth = 80; // we're using square images so set to 80 rather than the width of the image
lastX = lastX+lastWidth;
}
这导致的问题是,在这个循环之后,我必须在 UIScrollView 上将 userInteractionEnabled 设置为 NO,这样我才能覆盖 touchesBegan 并检测触摸,但是这样做当然会禁用滚动,因此用户只能看到前 6 个图像左右.
有没有办法可以重新启用滚动? photoScroller.scrollEnabled = YES;由于用户交互已被禁用,因此无效。
...
我尝试的第二种方法是为每个图像使用一个 UIButton,在这种情况下循环的代码如下:
for (i=0; i<[imageArray count]; i++) {
// get the image
UIImage *theImage = [imageArray objectAtIndex:i];
// figure out the size for scaled down version
float aspectRatio = maxImageHeight / theImage.size.height;
float thumbWidth = theImage.size.width * aspectRatio;
float thumbHeight = maxImageHeight;
lastX = lastX+10;
// Scale the image down
UIImage *thisImage = [theImage imageByScalingProportionallyToSize:CGSizeMake(thumbWidth, thumbHeight)];
// Create an 80x80 UIButton to hold the image, positioned 10px from the edge of the previous one
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(lastX, 10, 80, 80)];
button.clipsToBounds = YES;
button.contentMode = UIViewContentModeTopLeft;
[button setImage:thisImage forState:UIControlStateNormal];
[button setImage:thisImage forState:UIControlStateHighlighted];
[button addTarget:self action:@selector(tapImage:) forControlEvents:UIControlEventTouchUpInside];
// add to the scroller;
[photoScroller addSubview:button];
// release
[button release];
// set variables ready for the next one
//lastWidth = thisImage.size.width;
lastWidth = 80; // we're using square images so set to 80 rather than the width of the image
lastX = lastX+lastWidth;
}
现在这段代码几乎可以完美运行,唯一的问题是用户只有在触摸空白时才能滚动。
有什么办法可以做到,如果用户在 UIButton 上拖动它仍然会滚动 UIScrollView?
【问题讨论】:
标签: iphone cocoa-touch uiscrollview