2012-03-16 6 views
1

ボタンをタッチする必要があるアプリが忙しいですが、(アプリ画面の背景にある)ボタンの外側をタッチすると警告が表示されます。あなたがビューにジェスチャー認識器を追加することができますバックグラウンドタップの検出

MyButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    MyButton.frame = CGRectMake(0, 0, 100, 100); 
    [MyButton setImage:[UIImage imageNamed:@"tap.png"] forState:nil]; 
    [self.view addSubview:MyButton]; 

    [MyButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside]; 

答えて

4

誰がどのような背景

ボタンにタップを検出するために、知っています。

など。

// in viewDidLoad: 
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapped:)]; 
tapRecognizer.numberOfTapsRequired = 1; 
[self.view addGestureRecognizer:tapRecognizer]; 

- (void)backgroundTapped:(UITapGestureRecognizer*)recognizer { 
    // display alert 
} 

何もそれにジェスチャー認識器を持っているボタンの後ろにフルサイズUIViewを持っている試みることができる:

// in viewDidLoad: 
UIView *backgroundView = [[UIView alloc] initWithFrame:self.view.bounds]; 
backgroundView.backgroundColor = [UIColor clearColor]; 
backgroundView.opaque = NO; 
[self.view addSubview:backgroundView]; 

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapped:)]; 
tapRecognizer.numberOfTapsRequired = 1; 
[backgroundView addGestureRecognizer:tapRecognizer]; 

- (void)backgroundTapped:(UITapGestureRecognizer*)recognizer { 
    // display alert 
} 

これはself.viewにジェスチャー認識器を追加するより良い仕事かもしれません。

+0

:ジェスチャ認識は、私はわずかに異なる溶液を使用&他のUI要素の接触(Iは、ペン先から読み込んだ)

A window delivers touch events to a gesture recognizer before it delivers them to the hit-tested view attached to the gesture recognizer. Generally, if a gesture recognizer analyzes the stream of touches in a multi-touch sequence and does not recognize its gesture, the view receives the full complement of touches 

私のボタンを捕獲します私のボタンに触れて、アラート(nslog)が表示されます.iは、ボタンではなく背景に触れましたか? – Frenck

+0

ええと私はそれについて疑問に思っていましたが、前にも同様のことをやったので少し驚きました。私は考える必要があります。 – mattjgalloway

+0

uibuttonはプログラムでスクリプト化されています。インタフェースビルダーはありません。 HTMLではz-indexを使うこともできますが、これはobjective-cでも可能ですか? – Frenck

0

UIViewのカスタムサブクラスを作成し、それを透明にしてタッチハンドラで作成し、ボタンの下に新しいビューサブクラスのフルサイズのインスタンスを配置できます。その後、タッチダウンイベントが表示されるたびに、そのサブビューでメインビューコントローラに(委任を介して)メッセージを送信させることができます。ボタンはこのサブビューの上にあるので、ボタンをタップするとサブビューは何もしません。

0

最初の答えで解決策を見て、それをテストしました。それは私のために働かなかった。私はのNSLogを配置し、場合私はbackgroundtappedで

UIButton *invisibleBtn = [[UIButton alloc] initWithFrame:self.view.bounds]; 
invisibleBtn.titleLabel.text = @""; 
invisibleBtn.backgroundColor = [UIColor clearColor]; // no tap events if this is not set, bizarre 
[invisibleBtn addTarget:self action:@selector(backgroundTapped:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:invisibleBtn]; 
[self.view sendSubviewToBack:invisibleBtn]; 
関連する問題