How do I handle event when user touch up outside the UIView?

15,290

Solution 1

You should create a custom UIButton that takes up the whole screen. Then add your subview on top of that button. Then when the user taps outside of the subview they will be tapping the button.

For example, make the button like this:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(yourhidemethod:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"" forState:UIControlStateNormal];
button.frame = self.view.frame;
[self.view addSubview:button];

(where yourhidemethod: is the name of the method that removes your subview.) Then add your subview on top of it.


Update: It looks like you're wanting to know how to detect where touches are in a view. Here's what you do:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{   
  UITouch *touch = [touches anyObject];
  CGPoint touchPoint = [touch locationInView:self]; //location is relative to the current view
  // do something with the touched point 
}

Solution 2

Put it in full-screen transparent view and handle touches for it.

Solution 3

One idea is to have an invisible view(uicontrol) that is as big as the screen which then holds this custom popup.

Solution 4

It sounds like you'd be better served by deriving your menu from UIControl rather than UIView. That would simplify the touch handling, and all you'd have to do in this case would be to set a target and action for UIControlEventTouchUpOutside. The target could be the menu itself, and the action would hide or dismiss the menu.

Share:
15,290
Siarhei Fedartsou
Author by

Siarhei Fedartsou

Updated on June 04, 2022

Comments

  • Siarhei Fedartsou
    Siarhei Fedartsou almost 2 years

    I have a custom popup menu in my iOS application. It is UIView with buttons on it. How do I handle event when user touch up outside this view? I want to hide menu at this moment.