How to selectively swallow touches in Kobold2D? - kobold2d

In my top layer I have a 'Back button' sprite which should receive touches. Normally all other touches should pass through to lower layers, but if this Back button receives a tap gesture then it should swallow the touch.
Currently any touches on the Back button are also being received as touches on the layer beneath.
Top layer:
-(id) init {
if ((self = [super init])) {
[self scheduleUpdate];
// Initialize KKInput
KKInput* input = [KKInput sharedInput];
input.gestureTapEnabled = input.gesturesAvailable;
...
}
return self;
}
...
-(void) update:(ccTime)delta
{
KKInput* input = [KKInput sharedInput];
if (input.gestureTapRecognizedThisFrame) {
CCLOG(#"Top layer tap recognized");
if ([self.backButton containsPoint:input.gestureTapLocation]) {
CCLOG(#"Top layer Back Button tap recognized");
}
}
}
Lower layer
-(id) init {
if ((self = [super init])) {
[self scheduleUpdate];
// Initialize KKInput
KKInput* input = [KKInput sharedInput];
input.gestureTapEnabled = input.gesturesAvailable;
...
}
return self;
}
...
-(void) update:(ccTime)delta
{
KKInput* input = [KKInput sharedInput];
if (input.gestureTapRecognizedThisFrame) {
CCLOG(#"Lower layer tap recognized");
}
}
If I tap somewhere other than the Back button, the output is what I want:
2012-10-16 10:58:03.747 MyApp[13838:707] Top layer tap recognized
2012-10-16 10:58:03.749 MyApp[13838:707] Lower layer tap recognized
But if I tap on the Back button, the tap isn't swallowed by the button:
2012-10-16 10:49:23.426 MyApp[13838:707] Top layer tap recognized
2012-10-16 10:49:23.429 MyApp[13838:707] Top layer Back Button tap recognized
2012-10-16 10:49:23.434 MyApp[13838:707] Lower layer tap recognized

To clear the gesture state, you can turn it off and back on again. This should do the trick if you add this where you process the first tap gesture:
input.gestureTapEnabled = NO;
input.gestureTapEnabled = YES;

Related

How to access to app default gesture recognizers

I have created simple single view application and added just one button to view.
Next i used next code to determine all subviews and it's gesture recognizers:
-(void) debug:(UIView*) view{
for(UIGestureRecognizer* g in view.gestureRecognizers)
{
NSLog(#"base view gr=%# gr_view=%#",NSStringFromClass ([g class]),g.view);
}
for (UIView* sub in view.subviews) {
NSLog(#"%#.subview=%#",NSStringFromClass ([view class]),NSStringFromClass ([sub class]));
for(UIGestureRecognizer* g in sub.gestureRecognizers)
{
NSLog(#" | gr=%# gr_view=%#",NSStringFromClass ([g class]),g.view);
}
[self debug:sub];
}
}
But the log shows NO ONE gesture recognizer in existing view and it's subviews. I wold like to have access to default app gesture recognizers, how can i do this?

how to check that any of the button is clicked or not in iphone application

I have six button i want that user must select any of the six button before moving to next screen if it does not select any then it should not move to next screen I have read to use BOOL flag but this show which button is clicked i want that if any of the six buttons is clicked then user can move to next screen
-(IBAction)locationOneButtonAction{
// your stuff
_flag = YES;
}
-(IBAction)locationTwoButtonAction{
// your stuff
_flag = YES;
}
I think the best solution this problem is to declare a bool for your class (let's say it is called "ClickViewController" like (so at the top)
#interface ClickViewController () {
bool wasClicked;
}
...
-(IBAction)locationOneButtonAction{
// your stuff
wasClicked = YES;
}
Then when the button that should move to the next page is clicked utilize a method like this.
-(void)nextPageClicked{
if (wasClicked){
[self performSegueWithIdentifier:#"segueIdentifier" sender: self];
} else {
// do something else here, like tell the user why you didn't move them
}
}
This means that you cannot draw the segue from the button to the next view. If you are using storyboards, this means that you can't draw the segue from the button that is supposed to move it to the next view, rather you should draw it from the view controller icon to the next view. Then select the segue, name it, and use the method above with the name.
I'm also not sure if you mean that you want each of the buttons to move to the next view, if that is the case, you can use basically the same code, but just put the code [self performSegueWithIdentifier:#"segueIdentifier" sender: self]; line in action for the button.
Hopefully this helps.
Intially add BOOL _flag; int curIndex; in .h file.
Now add intially _flag = FALSE; in viewDidLoad method as it indicate no button clicked.
Make userInteractionEnabled for each button to be able to click and add tag to each button.
Now in action method of each click of button do this:
(IBAction)locationOneButtonAction:(id)sender{
curIndex = [sender tag]; //which button clicked
// your stuff
_flag = TRUE;
}
-(IBAction)locationTwoButtonAction{
curIndex = [sender tag]; //which button clicked
// your stuff
_flag = YES;
}
........
........
Now check like this if button clicked:
if(_flag)
{
NSLog(#"Button clicked with tag: %d",curIndex);
}
else
{
NSLog(#"Not any Button clicked");
}

Why does UINavigationBar steal touch events?

I have a custom UIButton with UILabel added as subview. Button perform given selector only when I touch it about 15points lower of top bound. And when I tap above that area nothing happens.
I found out that it hasn't caused by wrong creation of button and label, because after I shift the button lower at about 15 px it works correctly.
UPDATE I forgot to say that button located under the UINavigationBar and 1/3 of upper part of the button don't get touch events.
Image was here
View with 4 buttons is located under the NavigationBar. And when touch the "Basketball" in top, BackButton get touch event, and when touch "Piano" in top, then rightBarButton (if exists) get touch. If not exists, nothing happened.
I didn't find this documented feature in App docs.
Also I found this topic related to my problem, but there is no answer too.
I noticed that if you set userInteractionEnabled to OFF, the NavigationBar doesn't "steal" the touches anymore.
So you have to subclass your UINavigationBar and in your CustomNavigationBar do this:
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if ([self pointInside:point withEvent:event]) {
self.userInteractionEnabled = YES;
} else {
self.userInteractionEnabled = NO;
}
return [super hitTest:point withEvent:event];
}
Info about how to subclass UINavigationBar you can find here.
I found out the answer here(Apple Developer Forum).
Keith at Apple Developer Technical Support, on 18th May 2010 (iPhone OS 3):
I recommend that you avoid having touch-sensitive UI in such close proximity to the nav bar or toolbar. These areas are typically known as "slop factors" making it easier for users to perform touch events on buttons without the difficulty of performing precision touches. This is also the case for UIButtons for example.
But if you want to capture the touch event before the navigation bar or toolbar receives it, you can subclass UIWindow and override:
-(void)sendEvent:(UIEvent *)event;
Also I found out,that when I touch the area under the UINavigationBar, the location.y defined as 64,though it was not.
So I made this:
CustomWindow.h
#interface CustomWindow: UIWindow
#end
CustomWindow.m
#implementation CustomWindow
- (void) sendEvent:(UIEvent *)event
{
BOOL flag = YES;
switch ([event type])
{
case UIEventTypeTouches:
//[self catchUIEventTypeTouches: event]; perform if you need to do something with event
for (UITouch *touch in [event allTouches]) {
if ([touch phase] == UITouchPhaseBegan) {
for (int i=0; i<[self.subviews count]; i++) {
//GET THE FINGER LOCATION ON THE SCREEN
CGPoint location = [touch locationInView:[self.subviews objectAtIndex:i]];
//REPORT THE TOUCH
NSLog(#"[%#] touchesBegan (%i,%i)", [[self.subviews objectAtIndex:i] class],(NSInteger) location.x, (NSInteger) location.y);
if (((NSInteger)location.y) == 64) {
flag = NO;
}
}
}
}
break;
default:
break;
}
if(!flag) return; //to do nothing
/*IMPORTANT*/[super sendEvent:(UIEvent *)event];/*IMPORTANT*/
}
#end
In AppDelegate class I use CustomWindow instead of UIWindow.
Now when I touch area under navigation bar, nothing happens.
My buttons still don't get touch events,because I don't know how to send this event (and change coordinates) to my view with buttons.
Subclass UINavigationBar and add this method. It will cause taps to be passed through unless they are tapping a subview (such as a button).
-(UIView*) hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *v = [super hitTest:point withEvent:event];
return v == self? nil: v;
}
The solution for me was the following one:
First:
Add in your application (It doesn't matter where you enter this code) an extension for UINavigationBar like so:
The following code just dispatch a notification with the point and event when the navigationBar is being tapped.
extension UINavigationBar {
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "tapNavigationBar"), object: nil, userInfo: ["point": point, "event": event as Any])
return super.hitTest(point, with: event)
}
}
Then in your specific view controller you must listen to this notification by adding this line in your viewDidLoad:
NotificationCenter.default.addObserver(self, selector: #selector(tapNavigationBar), name: NSNotification.Name(rawValue: "tapNavigationBar"), object: nil)
Then you need to create the method tapNavigationBar in your view controller as so:
func tapNavigationBar(notification: Notification) {
let pointOpt = notification.userInfo?["point"] as? CGPoint
let eventOpt = notification.userInfo?["event"] as? UIEvent?
guard let point = pointOpt, let event = eventOpt else { return }
let convertedPoint = YOUR_VIEW_BEHIND_THE_NAVBAR.convert(point, from: self.navigationController?.navigationBar)
if YOUR_VIEW_BEHIND_THE_NAVBAR.point(inside: convertedPoint, with: event) {
//Dispatch whatever you wanted at the first place.
}
}
PD: Don't forget to remove the observation in the deinit like so:
deinit {
NotificationCenter.default.removeObserver(self)
}
That's it... That's a little bit 'tricky', but it's a good workaround for not subclassing and getting a notification anytime the navigationBar is being tapped.
I just wanted to share another prospective to solving this problem. This is not a problem by design, but it was meant to help user get back or navigate. But we need to put things tightly in or below nav bar and things look sad.
First lets look at the code.
class MyNavigationBar: UINavigationBar {
private var secondTap = false
private var firstTapPoint = CGPointZero
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
if !self.secondTap{
self.firstTapPoint = point
}
defer{
self.secondTap = !self.secondTap
}
return super.pointInside(firstTapPoint, withEvent: event)
}
}
You might be see why am i doing second touch handling. There is the recipe to the solution.
Hit test is called twice for a call. The first time the actual point on the window is reported. Everything goes well. On the second pass, this happens.
If system sees a nav bar and the hit point is around 9 pixels more on Y side, it tries to decrease that gradually to below 44 points which is where the nav bar is.
Take a look at the screen to be clear.
So theres a mechanism that will use nearby logic to the second pass of hittest. If we can know its second pass and then call the super with first hit test point. Job done.
The above code does that exactly.
There are 2 things that might be causing problems.
Did you try setUserInteractionEnabled:NO for the label.
Second thing i think might work is apart from that after adding label on top of button you can send the label to back (it might work, not sure although)
[button sendSubviewToBack:label];
Please let me know if the code works :)
Your labels are huge. They start at {0,0} (the left top corner of the button), extend over the entire width of the button and have a height of the entire view. Check your frame data and try again.
Also, you have the option of using the UIButton property titleLabel. Maybe you are setting the title later and it goes into this label rather than your own UILabel. That would explain why the text (belonging to the button) would work, while the label would be covering the rest of the button (not letting the taps go through).
titleLabel is a read-only property, but you can customize it just as your own label (except perhaps the frame) including text color, font, shadow, etc.
This solved my problem..
I added hitTest:withEvent: code to my navbar subclass..
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
int errorMargin = 5;// space left to decrease the click event area
CGRect smallerFrame = CGRectMake(0 , 0 - errorMargin, self.frame.size.width, self.frame.size.height);
BOOL isTouchAllowed = (CGRectContainsPoint(smallerFrame, point) == 1);
if (isTouchAllowed) {
self.userInteractionEnabled = YES;
} else {
self.userInteractionEnabled = NO;
}
return [super hitTest:point withEvent:event];
}
Extending Alexander's solution:
Step 1. Subclass UIWindow
#interface ChunyuWindow : UIWindow {
NSMutableArray * _views;
#private
UIView *_touchView;
}
- (void)addViewForTouchPriority:(UIView*)view;
- (void)removeViewForTouchPriority:(UIView*)view;
#end
// .m File
// #import "ChunyuWindow.h"
#implementation ChunyuWindow
- (void) dealloc {
TT_RELEASE_SAFELY(_views);
[super dealloc];
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (UIEventSubtypeMotionShake == motion
&& [TTNavigator navigator].supportsShakeToReload) {
// If you're going to use a custom navigator implementation, you need to ensure that you
// implement the reload method. If you're inheriting from TTNavigator, then you're fine.
TTDASSERT([[TTNavigator navigator] respondsToSelector:#selector(reload)]);
[(TTNavigator*)[TTNavigator navigator] reload];
}
}
- (void)addViewForTouchPriority:(UIView*)view {
if ( !_views ) {
_views = [[NSMutableArray alloc] init];
}
if (![_views containsObject: view]) {
[_views addObject:view];
}
}
- (void)removeViewForTouchPriority:(UIView*)view {
if ( !_views ) {
return;
}
if ([_views containsObject: view]) {
[_views removeObject:view];
}
}
- (void)sendEvent:(UIEvent *)event {
if ( !_views || _views.count == 0 ) {
[super sendEvent:event];
return;
}
UITouch *touch = [[event allTouches] anyObject];
switch (touch.phase) {
case UITouchPhaseBegan: {
for ( UIView *view in _views ) {
if ( CGRectContainsPoint(view.frame, [touch locationInView:[view superview]]) ) {
_touchView = view;
[_touchView touchesBegan:[event allTouches] withEvent:event];
return;
}
}
break;
}
case UITouchPhaseMoved: {
if ( _touchView ) {
[_touchView touchesMoved:[event allTouches] withEvent:event];
return;
}
break;
}
case UITouchPhaseCancelled: {
if ( _touchView ) {
[_touchView touchesCancelled:[event allTouches] withEvent:event];
_touchView = nil;
return;
}
break;
}
case UITouchPhaseEnded: {
if ( _touchView ) {
[_touchView touchesEnded:[event allTouches] withEvent:event];
_touchView = nil;
return;
}
break;
}
default: {
break;
}
}
[super sendEvent:event];
}
#end
Step 2: Assign ChunyuWindow instance to AppDelegate Instance
Step 3: Implement touchesEnded:widthEvent: for view with buttons, for example:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded: touches withEvent: event];
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView: _buttonsView]; // a subview contains buttons
for (UIButton* button in _buttons) {
if (CGRectContainsPoint(button.frame, point)) {
[self onTabButtonClicked: button];
break;
}
}
}
Step 4: call ChunyuWindow's addViewForTouchPriority when the view we care about appears, and call removeViewForTouchPriority when the view disappears or dealloc, in viewDidAppear/viewDidDisappear/dealloc of ViewControllers, so _touchView in ChunyuWindow is NULL, and it is the same as UIWindow, having no side effects.
An alternative solution that worked for me, based on the answer provided by Alexandar:
self.navigationController?.barHideOnTapGestureRecognizer.enabled = false
Instead of overriding the UIWindow, you can just disable the gesture recogniser responsible for the "slop area" on the UINavigationBar.
Give a extension version according to Bart Whiteley. No need to subclass.
#implementation UINavigationBar(Xxxxxx)
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *v = [super hitTest:point withEvent:event];
return v == self ? nil: v;
}
#end
The following worked for me:
self.navigationController?.isNavigationBarHidden = true

activate ccTouchesBegan with a button in cocos2d and make it work just one time

I want to make something happen with ccTouchesBegan but i want to restrict that action to a button, meaning that the action by the button should trigger ccTouchesBegan but only one time. After the code inside ccTouchesBegan has finished, the interface should go back to normal and wait for the button to be pressed to trigger the action again.
I have made the button trigger ccTouchesBegan when its pressed but the problem is that once the button is pressed, the code inside ccTouchesBegan keeps working and doing the same thing from then on when a touch action on the simulator is done.
This is the code that i have so far.
this is a flag method that i have created so that i know the button has been pressed and i can control the actions on ccTouchesBegan.
- (void) selector{
click = true;
}
this is the button which calls the method selector.
- (void) button{
CCMenuItemImage *touchesMovedButton = [CCMenuItemImage itemFromNormalImage:#"ActionButton-Normal.png"
selectedImage:#"ActionButton-Selected.png"
target:self
selector:#selector(selector)
];
CCMenu *selectorButton = [CCMenu menuWithItems: touchesMovedButton, nil];
selectorButton.position = ccp(64, 64);
[self addChild: selectorButton];
}
and this is the method ccTouchesBegan
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
//this part doesn't let the interface start the ccTouchesBegan code until the button has been pressed.
if (click == false) {
return;
}
// the else code starts when the button has been pressed.
else{
CCLOG(#"you have touched the interface!!");
}
}
That's the code, the interface doesn't do any action until the button is pressed but after it's pressed it keeps printing the CCLOG each time i touch the interface. i just want it to do it once and then when i press the button again it should do it just one time again.
does anyone know how to do this? or maybe point out my mistake?
You simply have the logical mistake. Use the Code below in the ccTouchesBegan It would work perfectly as you need...
if (click == false)
{
return;
}
// the else code starts when the button has been pressed.
else if(click == true)
{
CCLOG(#"you have touched the interface!!");
click=false; // You need to make false if you want to make touch single time enabled
}

iPhone: Combining MKMapView with another UITapGestureRecognizer

i am trying to implement my own gesture recognizer in addition to the one already used by the MKMapView. Right now i can tap on the map and set a pin. This behavior is realized by my UITapGestureRecognizer. When i tap on a pin that already exists, my gesture recognizer does nothing, but instead the callout bubble of this pin is shown. The UIGestureRecognizerDelegate looks like this:
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if (gestureRecognizer == self.tapRecognizer)
{
bool hitAnnotation = false;
int count = [self.mapView.annotations count];
int counter = 0;
while (counter < count && hitAnnotation == false )
{
if (touch.view == [self.mapView viewForAnnotation:[self.mapView.annotations objectAtIndex:counter]])
{
hitAnnotation = true;
}
counter++;
}
if (hitAnnotation)
{
return NO;
}
}
return YES;
}
This works fine. My only problem are the callout bubbles of the pins and the double tap. Normally the double tap is used for zooming in. This still works but in addition to this, i also get a new pin. Is there any way to avoid this?
The other problem occurs with the callout bubble of a pin. I can open the bubble by tapping on the pin without setting a new pin at this place (see code above) but when i want to close the bubble by tapping on it, another pin is set. My problem is, that i cannot check with touch.view , if the user tapped on a callout bubble, because it is not a regular UIView as far as i know. Any ideas or workarounds for this problem?
Thanks
I had the same problem as your first problem: distinguishing double taps from single taps in an MKMapView. What I did was the following:
[doubleTapper release];
doubleTapper = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(mapDoubleTapped:)];
doubleTapper.numberOfTapsRequired = 2;
doubleTapper.delaysTouchesBegan = NO;
doubleTapper.delaysTouchesEnded = NO;
doubleTapper.cancelsTouchesInView = NO;
doubleTapper.delegate = self;
[mapTapper release];
mapTapper = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(mapTapped:)];
mapTapper.numberOfTapsRequired = 1;
mapTapper.delaysTouchesBegan = NO;
mapTapper.delaysTouchesEnded = NO;
mapTapper.cancelsTouchesInView = NO;
[mapTapper requireGestureRecognizerToFail:doubleTapper];
and then implemented the following delegate method:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
Using requireGestureRecognizerToFail: allows the app to distinguish single taps from double taps and implementing gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: ensures that double taps are still forwarded to the MKMapView so that it continues zooming normally. Note that doubleTapper doesn't actually do anything (in my case, except log debug messages). It's simply a dummy UIGestureRecognizer that's used to help separate single taps from double taps.