NSObjectで定義される-performSelector:withObjectメッソドを利用する。
タッチイベントを検出したいViewのid型インスタンス変数targetにアクションを起こしたいオブジェクトを格納し、ViewのSEL型インスタンス変数actionにオブジェクトのメソッドを格納する。
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;
myView.action = @selector(touched);
}
- (void)touched
{
NSLog(@"----ログ2----");
}
@end
MyView.h
#import <UIKit/UIKit.h> @interface MyView : UIView @property id target; @property SEL action; @end
MyView.m
#import "MyView.h"
@implementation MyView
@synthesize target, action;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"----ログ1----");
[target performSelector:action];
}
@end
コメント