检测背景水龙头

时间:2012-03-16 23:01:58

标签: objective-c

我正忙着你需要触摸按钮的应用程序,但是当你触摸按钮外(在应用程序屏幕的背景上)我想显示警告。

有谁知道如何检测背景上的点击

按钮:

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

3 个答案:

答案 0 :(得分: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更好。

答案 1 :(得分:0)

您可以创建UIView的自定义子类,使其透明,但使用触摸处理程序,并将新视图子类的完整大小实例放在按钮下方。然后,只要看到触碰事件,您就可以让该子视图向主视图控制器发送消息(通过委托)。由于按钮位于此子视图的顶部,因此如果点按该按钮,子视图将不会执行任何操作。

答案 2 :(得分:0)

我在第一个答案中查看了解决方案并对其进行了测试。它对我不起作用。手势识别器捕获了我的按钮&其他UI元素触摸(我从nib加载)

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