cocoa-touch: How to find out which object was touched
Sorry, but a very basic beginner's question: Imagine having an UITextField and an UITextView. Then, imagine a transparent UIView placed above these TextField/View, so they won't respond if you touch them.
If you touch (as opposed to swipe or pinch etc) the UIView, I would like that whatever the user touches (i.e. TextField or View) becomes first responder. Is there a command like:
[objectThatWasTouched becomeFirstResponder];
?
I would need this in the following method. Right now, it is set so that UITextView becomes first responder, but I would like whatever object is touched to become the first responder:
- (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];
}
}
And finally, I would need to some kind of method to get rid of the first responder, i.e. depending on whatever is first responder. This will get only get rid of the firstresponder, when UITextView had been touched:
- (IBAction)hideK开发者_JAVA技巧eyboard
{
[aSwipeTextView resignFirstResponder];
[self.view bringSubviewToFront:canTouchMe];
}
UITouch *touch = [touches anyObject];
if (touch.view == mybutton){
NSLog(@"My Button pressed");
}
You can try something like this:
- (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 ...
}
Note: In this case myView should be userInteraction enabled(myView.userInteractionEnabled = YES) otherwise the touch event will be passed to its superView whose userInteraction is enabled.
UITouch *touch = [touches anyObject];
if (touch.view == myView){
NSLog(@"My myView touched");
}
精彩评论