2012-03-16 84 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];