UILabelやUIImageViewなどは、デフォルトでuserInteractionEnabledがNOになっています。これらのオブジェクトにUITapGestureRecognizerなどを追加した場合は、必ず、userInteractionEnabledにYESを設定しましょう。
1. userInteractionEnabledをYESにする
userInteractionEnabledはUIViewクラスのプロパティです。UILabelなどではデフォルト値がNOなのでそのままでは応答しません。YESに切り替えましょう。
UILabel * label =
[[UILabel alloc] initWithFrame:CGRectMake(x,y,w,h)];
label.userInteractionEnabled = YES;
UIImageView * leftArrowView =
[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left.gif"]];
leftArrowView.userInteractionEnabled = YES;
[[UILabel alloc] initWithFrame:CGRectMake(x,y,w,h)];
label.userInteractionEnabled = YES;
UIImageView * leftArrowView =
[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left.gif"]];
leftArrowView.userInteractionEnabled = YES;
2. UITapGestureRecognizerを追加する
タップイベントを検知すると、selfのleftActionが呼び出されます。
[leftArrowView addGestureRecognizer:
[[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(leftAction)]];
[[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(leftAction)]];
- (void)leftAction{
}
}
次のようにすると、leftActionにUITapGestureRecognizerのインスタンスが渡されます。UIGestureRecognizerのインスタンスのview属性で、送信元のオブジェクトがわかります。
[leftArrowView addGestureRecognizer:
[[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(leftAction:)]];
[[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(leftAction:)]];
- (void)leftAction: (UITapGestureRecognizer *)sender{
}
}