可可触摸:如何找出被触摸的对象

| 抱歉,但是是一个非常基本的初学者的问题:假设有一个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时,这将仅摆脱firstresponder:
    - (IBAction)hideKeyboard
{
    [aSwipeTextView resignFirstResponder];
    [self.view bringSubviewToFront:canTouchMe];

}
    
已邀请:
您可以尝试如下操作:
- (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 ...
}
    
UITouch *touch = [touches anyObject];

if (touch.view == mybutton){

        NSLog(@\"My Button pressed\");
}
    
注意:在这种情况下,应将myView启用userInteraction(myView.userInteractionEnabled = YES),否则触摸事件将传递给已启用userInteraction的其superView。 UITouch * touch = [触摸anyObject]; 如果(touch.view == myView){
    NSLog(@\"My myView touched\");
}     

要回复问题请先登录注册