我有一个 UITableView,其中一个 UITableViewCells 包含一个 UIScrollView 和一个 UIPageControl;以便用户在浏览表格时可以水平滚动两页。
我的问题是这样的 - 最初页面控件工作正常,当我浏览 ScrollView 中的页面时,我可以看到小点按预期移动。但是,当我向上或向下滚动表格时,页面控件始终重置回第一页。
这是因为我确定页面的方法使用scrollview.contentoffset.x来确定我所在的页面,并且一旦我开始向上或向下移动表格,contentoffset.x总是返回0。实际的 ScrollView 本身物理上不会向左或向右移动(内容保留在正确的页面上);所以我不确定为什么 contentoffset.x 总是重置为 0?
这是我在 cellForRowAtIndexPath 中的代码
UIScrollView* previewScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, tideRowHeight)];
[previewScrollView setContentSize:CGSizeMake(640, tideRowHeight)];
[previewScrollView setPagingEnabled:YES];
[previewScrollView setTag:0022];
[previewScrollView setShowsHorizontalScrollIndicator:NO];
[previewScrollView setDelegate:self];
[previewScrollView addSubview:todayTidesTime];
[previewScrollView addSubview:todayTidesHeight];
[previewScrollView addSubview:todayTidesHL];
[[cell contentView] addSubview:previewScrollView];
UIPageControl *tidesPageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 130, cell.frame.size.width, 10)];
[tidesPageControl setNumberOfPages:2];
[tidesPageControl setCurrentPageIndicatorTintColor:[UIColor blackColor]];
[tidesPageControl setPageIndicatorTintColor:[UIColor grayColor]];
[[cell contentView] addSubview:tidesPageControl];
self.pageControl = tidesPageControl;
这是我的代码,它确定我所在的当前页面:
(void)scrollViewDidScroll:(UIScrollView *)sender {
CGFloat pageWidth = sender.frame.size.width;
int page = floor((sender.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
NSLog(@"content offset x %f", sender.contentOffset.x);
NSLog(@"scroll view did scroll %d", page);
self.pageControl.currentPage = page;
}
当我向上或向下滚动 UITableView 时(页面控件位于第二页),日志输出以下内容:
2013-10-17 21:47:36.238 Vic [61180:a0b] content offset x 319.500000
2013-10-17 21:47:36.238 Vic [61180:a0b] page we are on 1
2013-10-17 21:47:36.254 Vic [61180:a0b] content offset x 320.000000
2013-10-17 21:47:36.254 Vic [61180:a0b] page we are on 1
2013-10-17 21:47:40.173 Vic [61180:a0b] content offset x 0.000000 <------scroll up here!
2013-10-17 21:47:40.173 Vic [61180:a0b] page we are on 0 <------ my problem!
2013-10-17 21:47:40.189 Vic [61180:a0b] content offset x 0.000000
为什么 contentoffset.x 会重置为零?
最佳答案
解决了;因为我有一个 UIScrollView 和一个 UITableView 在一起,并且 UITableView 继承自 UIScrollView,所以表和 ScrollView 都调用我的scrollViewDidScroll 方法。因此,检查 rollViewDidScroll 的 sender 参数的类名可以解决问题 - 如果从表中调用它(即 sender 是 UITableView),则不执行任何操作。否则如果是UIScrollView,则检查页面控件等。
关于iphone - 滚动 UITableView 时 UIScrollView 内容偏移 x 设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19424818/