タッチを検出したいViewにプロトコルでアクションを起こしたいオブジェクトのメソッドを実装して実現させる。
MyViewController.h
#import <UIKit/UIKit.h> #import "MyView.h" @interface MyViewController : UIViewController @property MyView* myView; @end
MyViewController.m
#import "MyViewController.h" @interface MyViewController () @end @implementation MyViewController @synthesize myView; - (void)viewDidLoad { [super viewDidLoad]; myView = [[MyView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)]; myView.backgroundColor = [UIColor yellowColor]; [self.view addSubview:myView]; myView.target = self; } - (void)touched { NSLog(@"----ログ2----"); } @end
MyView.h
#import <UIKit/UIKit.h> @protocol TouchEvent <NSObject> - (void)touched; @end @interface MyView : UIView @property id<TouchEvent> target; @end
MyView.m
@implementation MyView @synthesize target; - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { } return self; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"----ログ1----"); [target touched]; } @end
コメント