Search code examples
iosuibuttontapnearest-neighbor

Pass touch to nearest UIButton?


I am trying to create a view with multiple UIButtons where any tap would be registered as a tap on the nearest UIButton. I have been unsuccessful so far, and I am hoping you guys/gals have some knowledge on standard approaches/methods used to do what I am trying to do.


Solution

  • You could use the Touches Began method:

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
      {
          // Get the CGPoint of the touch:
          UITouch touch = [touches anyObject];
          CGPoint touchPoint = [touch locationInView:self.view];
    
          // Loop through an array containing your buttons and see if we tapped
          // one of these buttons, if so, do nothing and let the button handle the tap
          for (UIButton button in MyButtonsArray){
            if(CGRectContainsPoint(button.frame, touchPoint)) {
                 return;
              } 
          }
    
         // if the loop completes without returning, you tapped something other than a button
         // so add code here that uses the mathematical distance formula to 
         // calculate which button is the closest to the tap point. 
    
    
      }
    

    You have all the necessary "data" in terms of coordinates of the button and coordinates of the touch point to calculate the closest button to the touch point.