【发布时间】:2013-10-06 19:41:48
【问题描述】:
我正在尝试构建一个带有分页功能的简单 UIScrollView,以便在 3 个图像之间水平滚动。 棘手的部分是我希望每个图像都可以点击并捕获点击事件。
我的技术是创建 3 个 UIButton,每个都包含 UIImage。给每个按钮一个标签并设置一个动作。
问题:我可以捕捉到点击事件 - 但是它不能滚动!
这是我的代码:
- (void) viewDidAppear:(BOOL)animated {
_imageArray = [[NSArray alloc] initWithObjects:@"content_01.png", @"content_02.png", @"content_03.png", nil];
for (int i = 0; i < [_imageArray count]; i++) {
//We'll create an imageView object in every 'page' of our scrollView.
CGRect frame;
frame.origin.x = _contentScrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = _contentScrollView.frame.size;
//
//get the image to use, however you want
UIImage* image = [UIImage imageNamed:[_imageArray objectAtIndex:i]];
UIButton* button = [[UIButton alloc] initWithFrame:frame];
//set the button states you want the image to show up for
[button setImage:image forState:UIControlStateNormal];
[button setImage:image forState:UIControlStateHighlighted];
//create the touch event target, i am calling the 'productImagePressed' method
[button addTarget:self action:@selector(imagePressed:)
forControlEvents:UIControlEventTouchUpInside];
//i set the tag to the image #, i was looking though an array of them
button.tag = i;
[_contentScrollView addSubview:button];
}
//Set the content size of our scrollview according to the total width of our imageView objects.
_contentScrollView.contentSize = CGSizeMake(_contentScrollView.frame.size.width * [_imageArray count], _contentScrollView.frame.size.height);
_contentScrollView.backgroundColor = [ENGAppDelegate backgroundColor];
_contentScrollView.delegate = self;
}
【问题讨论】:
-
您是否已单步执行您的代码以确保 _contentScrollView.contentSize 符合您的预期?我认为此时 _contentScrollView.frame.size 计算不正确,因此您不会获得良好的价值。
-
我查过,计算正确!让我这样说:如果我在没有框架的情况下初始化按钮(所以没有显示图片),那么我会看到它滚动!
-
是否有可能如果我将按钮框架设置为与 ScrollView 一样的确切大小,那么它会完全阻止滚动,所以我没有得到滚动事件??
-
这对我来说似乎很奇怪。滚动视图根本不应该关心它的一个孩子的框架。
-
计算结束时的 _contentScrollView.frame 是什么?您是否碰巧将其设置为与内容一样大,而不仅仅是屏幕尺寸?
标签: ios uiscrollview