2012-03-16 90 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

你可以手勢識別器添加到視圖。

E.g.

// 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

在backgroundtapped我置於的NSLog和當我觸摸我的按鈕警報(nslog)顯示了..我觸摸了按鈕,而不是背景? – Frenck 2012-03-16 23:30:11

+0

嗯,我很想知道,雖然我有點驚訝,因爲我以前做過類似的事情,它的工作。我需要有一個想法,並建立一個測試... – mattjgalloway 2012-03-16 23:49:18

+0

uibutton編程腳本。沒有界面生成器。在HTML中,你可以使用z-index的東西,這在objective-c中也是可行的嗎? – Frenck 2012-03-17 11:01:57

0

您可以創建UIView的自定義子類,使其具有透明度,但帶有觸摸處理程序,並將該新視圖子類的全尺寸實例放置在按鈕下方。然後,只要發現觸發事件,子視圖就會向主視圖控制器發送一條消息(通過委派)。由於該按鈕位於此子視圖的頂部,因此如果輕按按鈕,子視圖將不會執行任何操作。

0

我在第一個答案中查看了解決方案並進行了測試。它不適合我。姿勢識別捕獲的我的按鈕&其他UI元素觸摸(我是從筆尖加載)

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 

我使用了略有不同的解決方案:

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];