【发布时间】:2010-06-22 13:24:14
【问题描述】:
我想在 UIViewController 子类中处理触摸(特别是水平滑动),但问题是控制器的视图包含一个覆盖整个屏幕的 UIScrollView,因此“touchesBegan:”和“touchesEnded:”事件在我的控制器中永远不会被调用。滚动视图只垂直滚动。
让它能够处理这些事件的最佳方法是什么?让我的 UIViewController 也继承自 UIScrollView 并根据需要处理触摸(并删除当前的滚动视图),或者使用 UIScrollView 子类代替我当前的滚动视图,这将为我需要的情况调用委托方法?还是有别的办法?
这是我当前的代码:
// View creation and adding to parent
NewViewController* newViewController = [[newViewController alloc] initWithNibName:@"NewViewController" bundle:nil];
[self.view addSubview:newViewController.view];
// NewViewController.h
@interface NewViewController : UIViewController {
IBOutlet UIScrollView* scrollView;
// other outlets and properties
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event;
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event;
在 IB 中,NewViewController 的视图包含滚动视图,其中包含所有其他出口(标签、按钮)... 目标是让 NewViewController 的 scrollView 调用 NewViewController 的 touchesBegan 和 touchesEnded 方法。
更新: ScrollViewSuite 帮助我了解了如何处理触摸回调。 UIScrollView 仅在触摸不滚动时才调用它们。
所以,三种情况:
- 倾斜滑动(即使是轻微的,只要滚动条出现):没有调用
touches方法 - 完全水平滑动(不出现滚动条):
touchesBegan、touchesMoved和touchesEnded被调用 - 任何不引起滚动的触摸(触摸而不移动,或水平移动)然后稍微垂直滑动:
touchesBegan、touchesMoved和touchesCancelled都会被调用;
可以通过将UIScrollView 的canCancelContentTouches 设置为FALSE 来避免取消触摸,但这显然只有在调用touchesBegan 时才有效,这意味着在第一种情况下仍然不会调用触摸方法。
但是UIScrollView 有一个名为delaysContentTouches 的属性,默认设置为TRUE,它会在触摸开始时稍等片刻,以查看是否会让他滚动。如果设置为FALSE,则在触摸开始时立即调用触摸方法,并允许子类根据需要处理它们。
TL;DR: 对我来说似乎最简单的方法(如果你不能使用UIGestureRecognizer)是继承UIScrollView,将其delayContentTouches 属性设置为@987654340 @ 并根据您的需要覆盖触摸功能(touchesShouldBegin / touchesShouldCancel 以及 touchesBegan / touchesMoved...)。
【问题讨论】:
-
scrollView 的 contentSize 属性在哪里设置?
-
在 NewViewController 的 viewDidLoad 中。我根据插座的大小放置插座,最后设置 scrollView 的内容高度。但是使用此代码滚动工作,唯一的问题是不调用触摸方法。
标签: iphone cocoa-touch uiviewcontroller uiscrollview