取れるようにするためには、UIScrollView のサブクラスを作成することにより実現できる。。。
と、書かれているが、どうもよく分からない。
とりあえず、手を動かせと言う事か
今回確認した内容を書いていく。
UIScrollView を継承するクラスを作成する(今回は MyScrollView と言う名前で作成)。
これは、普通の空クラスを作成すると同じ方法で作成。
この時に、継承元の指定を UIScrollView にする。
また、作成したクラス内に、タッチイベントを実装(オーバーライド)する。
#import <UIKit/UIKit.h> @interface MyScrollView : UIScrollView @end
#import "MyScrollView.h"
@implementation MyScrollView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// タッチ終了(タッチから外れた)イベント
// touchesBegan をオーバーライドしておかないと、これは動かない
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (!self.dragging) {
[self.nextResponder touchesEnded: touches withEvent:event];
}
[super touchesEnded: touches withEvent: event];
}
// タッチ開始イベント
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (!self.dragging) {
[self.nextResponder touchesBegan:touches withEvent:event];
}
[super touchesBegan:touches withEvent:event];
}
@end
後は、メインとなるクラスで、今回作成したクラスを使用するだけ。#import <UIKit/UIKit.h> @class MyScrollView; @interface ViewController : UIViewController<UIScrollViewDelegate> @property (strong, nonatomic) MyScrollView *scrollView; @end
#import "ViewController.h"
#import "MyScrollView.h"
@interface ViewController ()
@end
@implementation ViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.scrollView = [[MyScrollView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:self.scrollView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
# pragma mark - ScrollView Touch Events
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"touchesEnded!!");
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"touchesBegan!!");
}
@end
確認の際に詰まった点としては、サブクラスでタッチイベントをオーバーライドしているが、touchesBegan を実装していないと、touchesEnded のイベントが発生しない(つまり touchesEnded だけをオーバーライドしても動かない)。このことが分かるまでに、悩んでしまった。
ひとまず、これでタッチイベントが取得できるようになるので、後はこれまで通りのタッチイベントを処理する方法と同じように処理ができる。
0 件のコメント:
コメントを投稿