cocoa-touch:如何找出被触摸的对象

时间:2011-04-19 18:58:03

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

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

如果你触摸(而不是滑动或捏等)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];

}

3 个答案:

答案 0 :(得分:4)

UITouch *touch = [touches anyObject];

if (touch.view == mybutton){

        NSLog(@"My Button pressed");
}

答案 1 :(得分: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 ...
}

答案 2 :(得分:1)

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

UITouch * touch = [触及anyObject];

if(touch.view == myView){

    NSLog(@"My myView touched");

}