我最近遇到了无法从 UIScrollView
中注册触摸事件(touchesMoved
等)的问题。在与很多人交谈并阅读了大量帖子后,事实证明 UIScrollView
本身不接受触摸,而是需要将触摸传递给 UIScrollView
子类。
我是 objective-c 的新手,我花了很长时间思考如何定义子类(在单独的 .h/.m 文件中或以某种方式在 @interface 或其他东西中),以及 iOS 如何处理与响应链。
请让我描述一下我的具体情况,任何愿意用菜鸟语言解释我需要做什么的人都将不胜感激。
我的应用程序中只有一个页面,我将它的默认 UIView
更改为 UIScrollView
,所以如果我在 InterfaceBuidler
中检查它我看到的是我的 SampleViewController
和 UIScrollView
。我将 UIScrollView
链接到 SampleViewControler.h
的 @Interface
,如下所示:
#import <UIKit/UIKit.h>
@interface SampleViewController : UIViewController
{
}
@property (strong, nonatomic) IBOutlet UIScrollView *mainScroller;
@end
我在 SampleViewController.m
中引用了我的 UIScrollView
,如下所示:
#import "SampleViewController.h"
@interface SampleViewController ()
@end
@implementation SampleViewController
@synthesize mainScroller = _mainScroller;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"Movement!");
}
-(void)viewWillAppear:(BOOL)animated
{
[_mainScroller setContentOffset:CGPointMake(0,0) animated:YES];
}
如果我将 UIScrollView
的类更改为 UIView
,则会检测到触摸并触发一些 NSLog
消息。但是,一旦 UIView
设置回 UIScrollView
,触摸将被忽略。
据我了解,我需要使用以下代码设置 UIScrollView
的子类:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"Movement!");
}
...然后更改我的 SampleViewController.m 以获得代码:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self.nextResponder nextResponder] touchesMoved:touches withEvent:event];
}
但是,我真的不明白 1) 如何设置这样的子类,以及 2) 为什么这会起作用,因为我不明白为什么 [[self.nextResponder nextResponder] touchesMoved:touches withEvent: event];
将首先从 SampleViewController.m
中调用,因为我类似的 NSLog(@"Movement!");
语句永远不会执行。
我已经尝试了我能找到的所有教程,并且正在转向 SE 的专业知识!谢谢。
最佳答案
你想错了。如果您想知道 scrollView 何时移动,则无需对其进行子类化。 iOS 已在 UIScrollViewDelegate
中设置了您需要的所有方法。但是,如果您想说,为基于 scrollView 的项目选择 touchEvents,那完全没问题。然后,您只需要对 scrollView 中的项目进行子类化,然后在各自的类中选择 touchEvents。但是对于标准的 scrollView 方法,你应该这样设置:
.H
#import <UIKit/UIKit.h>
@interface SampleViewController : UIViewController<UIScrollViewDelegate>
{
}
@property (strong, nonatomic) IBOutlet UIScrollView *mainScroller;
@end
.M
#import "SampleViewController.h"
@interface SampleViewController ()
@end
@implementation SampleViewController
@synthesize mainScroller = _mainScroller;
-(void)viewDidLoad
{
self.mainScroller.delegate=self;//Adopt the delegate for the scrollView..this is the important line
}
然后只需实现 UIScrollViewDelegateMethods 来抓取移动等。当试图在 scrollView/tableView 中拾取 touchEvents 时会发生未定义的行为,因为 scrollView 本身已经在幕后实现了这些 touchEvents
查看开发者网站上的所有方法并在您的 .M 文件中实现它们。由于您在 viewDidLoad 中采用了委托(delegate),因此这些将是您的 scrollView 回调。我之前已经列出了其中的一些,但请继续查看 UIScrollViewDelegate Protocol site
– scrollViewDidScroll:
– scrollViewWillBeginDragging:
– scrollViewWillEndDragging:withVelocity:targetContentOffset:
– scrollViewDidEndDragging:willDecelerate:
– scrollViewShouldScrollToTop:
– scrollViewDidScrollToTop:
– scrollViewWillBeginDecelerating:
– scrollViewDidEndDecelerating:
关于ios - 如何设置 UIScrollView 的子类来响应触摸事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17077242/