【问题标题】:cocoa-touch: How to find out which object was touched可可触摸:如何找出被触摸的对象
【发布时间】:2011-04-19 18:58:02
【问题描述】:

抱歉,这是一个非常基本的初学者问题:想象一下有一个 UITextField 和一个 UITextView。然后,想象一个透明的 UIView 放置在这些 TextField/View 上方,所以如果你触摸它们,它们将不会响应。

如果您触摸(而不是滑动或捏合等)UIView,我希望用户触摸的任何内容(即 TextField 或 View)都成为第一响应者。有没有类似的命令:

[objectThatWasTouched becomeFirstResponder];?

我将在以下方法中需要它。现在,它被设置为 UITextView 成为第一响应者,但我希望任何被触摸的对象都成为第一响应者:

 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    [super touchesMoved:touches withEvent:event];

    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView:self.view];

    CGFloat deltaX = fabsf(gestureStartPoint.x - currentPosition.x); // will always be positive
    CGFloat deltaY = fabsf(gestureStartPoint.y - currentPosition.y); // will always be positive


    if (deltaY == 0 && deltaX == 0) {

        [self.view bringSubviewToFront:aSwipeTextView];
        [self.view bringSubviewToFront:noteTitle];
        [self.view bringSubviewToFront:doneEdit];


        [aSwipeTextView becomeFirstResponder];


    }


}

最后,我需要某种方法来摆脱第一响应者,即取决于第一响应者。当 UITextView 被触摸时,这只会摆脱第一响应者:

    - (IBAction)hideKeyboard
{
    [aSwipeTextView resignFirstResponder];
    [self.view bringSubviewToFront:canTouchMe];

}

【问题讨论】:

    标签: iphone objective-c cocoa-touch first-responder


    【解决方案1】:
    UITouch *touch = [touches anyObject];
    
    if (touch.view == mybutton){
    
            NSLog(@"My Button pressed");
    }
    

    【讨论】:

    【解决方案2】:

    你可以试试这样的:

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    
        [super touchesMoved:touches withEvent:event];
    
        UITouch *touch = [touches anyObject];
        CGPoint currentPosition = [touch locationInView:self.view];
    
        UIView *hitView = [self hitTest:currentPosition withEvent:event];
    
        if([hitView isKindOfClass:[UIResponder class]] && [hitView canBecomeFirstResponder]) {
           [hitView becomeFirstResponder];
        }
    
        // ... more code ...
    }
    

    【讨论】:

      【解决方案3】:

      注意:在这种情况下,myView 应该启用 userInteraction(myView.userInteractionEnabled = YES) 否则触摸事件将被传递到其启用 userInteraction 的 superView。

      UITouch *touch = [触摸任何对象];

      if (touch.view == myView){

          NSLog(@"My myView touched");
      

      }

      【讨论】:

        猜你喜欢
        • 2012-11-03
        • 1970-01-01
        • 1970-01-01
        • 2012-04-04
        • 1970-01-01
        • 1970-01-01
        • 2020-04-10
        • 2013-02-24
        • 1970-01-01
        相关资源
        最近更新 更多