using two finger pinch to zoom in collectionView Xcode - cocoa-touch

I have an app that has a collectionView inside a scrollView. I am using the following code to be able to zoom in and pan around.
-(void) viewDidLoad {
[super viewDidLoad];
twoFingerPinchA = [[UIPinchGestureRecognizer alloc]
initWithTarget:self
action:#selector(twoFingerPinch:)]
;
[self.view addGestureRecognizer:(twoFingerPinchA)];
}
-(void)twoFingerPinch:(UIPinchGestureRecognizer *)recognizer{
CGAffineTransform transform = CGAffineTransformMakeScale(twoFingerPinchA.scale, twoFingerPinchA.scale);
if (twoFingerPinchA.scale < 1) {
twoFingerPinchA.scale = 1;
}
if (twoFingerPinchA.scale >2) {
twoFingerPinchA.scale = 2;
}
self.scrolling.transform = transform;
}
This works well except when I am zoomed in and remove my fingers. When I put my two fingers back on the screen to zoom out or in again the view returns to not zoomed in. How can I get the view to stay zoomed in when I replace my two fingers on the screen to rezoom.
I have tried capturing the twoFingerPinchA.scale value which I can do. But I don't know how to set the initial value of the twoFingerPinchA.scale to that value as it alway returns to 1.
Any ideas?
So I am now trying to detect when two fingers touch the screen and when the two finger touch stops so I can save and insert the value of the twoFingerPinchA.scale.
However No matter what I put in I can't seem to detect the touches.
I have my controllers regular view, then I have a scroll view in it and then a collectionView inside of it.
I have enabled interaction and multiple touch for all views and tried to detect the touches in all view but don't get a call back. Here is my code.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(#"Event:%#",event);
// I don't even get this call back as a touch beginning on any view.
if ([[event touchesForView:self.view] count] >0) {
NSLog(#"touches");
}
}

So I figured this out.
First I used this code
-(void) viewWillAppear:(BOOL)animated{
NSString *pinchString = #"1.0";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:pinchString forKey:#"pinchValue"];
}
//this was to make sure that the pinchValue key had a value when the app is first installed.
then I put this
switch ([twoFingerPinchA state]) {
case UIGestureRecognizerStatePossible:
{
}
break;
case UIGestureRecognizerStateBegan:
{
NSString *inPinch = [[NSUserDefaults standardUserDefaults] objectForKey:#"pinchValue"];
float Pinch = [inPinch floatValue];
twoFingerPinchA.scale = Pinch;
}
break;
case UIGestureRecognizerStateChanged:
{
}
break;
case UIGestureRecognizerStateEnded:
{
NSString *pinchString = [NSString stringWithFormat:#"%f",twoFingerPinchA.scale];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:pinchString forKey:#"pinchValue"];
}
break;
case UIGestureRecognizerStateCancelled:
{
}
break;
case UIGestureRecognizerStateFailed:
{
}
break;
}
in my
-(void)twoFingerPinch:(UIPinchGestureRecognizer *)recognizer{}
This stores the value of the twoFingerPinchA.scale in usersDefaults when the pinch ends
and
sets the twoFingerPinchA.scales to that stored value when it begins again. From there it adjust up and down /in and out according to this value.
Works great

Related

Scroll Table View with a cell that was selected with a long press

I have a table view that I would like to scroll when a selected a cell and "pop" it out and move it around the table view. The table view scrolls just fine and the long press to select a cell works, but I'm not able to scroll the table view when I have a cell selected.
I read up on UIGestureRecognizerDelegate but I'm not sure that is making a difference. I also call these method
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
Here is part of my code:
- (IBAction)longPressGestureRecognized:(id)sender {
UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;
UIGestureRecognizerState state = longPress.state;
//longPress.delegate = self;
CGPoint location = [longPress locationInView:self.personTableView];
NSIndexPath *indexPath = [self.personTableView indexPathForRowAtPoint:location];
static UIView *snapshot = nil; ///< A snapshot of the row user is moving.
static NSIndexPath *sourceIndexPath = nil; ///< Initial index path, where gesture begins.
switch (state) {
case UIGestureRecognizerStateBegan: {
if (indexPath) {
sourceIndexPath = indexPath;
UITableViewCell *cell = [self.personTableView cellForRowAtIndexPath:indexPath];
// capture the color of the cell before blacking out
savedTextColor = cell.detailTextLabel.textColor;
// Take a snapshot of the selected row using helper method.
snapshot = [self customSnapshotFromView:cell];
// Add the snapshot as subview, centered at cell's center...
__block CGPoint center = cell.center;
snapshot.center = center;
snapshot.alpha = 0.0;
[self.personTableView addSubview:snapshot];
[UIView animateWithDuration:0.25 animations:^{
// Offset for gesture location.
center.y = location.y;
snapshot.center = center;
snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);
snapshot.alpha = 0.98;
// Black out.
cell.detailTextLabel.alpha = 0;
cell.textLabel.alpha = 0;
} completion:nil];
}
break;
}
case UIGestureRecognizerStateChanged: {
CGPoint center = snapshot.center;
center.y = location.y;
snapshot.center = center;
// Is destination valid and is it different from source?
if (indexPath && ![indexPath isEqual:sourceIndexPath]) {
// ... update data source.
[dataSingelton saveUpdatedPersonList:(int)indexPath.row sourceIndex:(int)sourceIndexPath.row];
//[[dataSingelton mutableDataArray] exchangeObjectAtIndex:indexPath.row withObjectAtIndex:sourceIndexPath.row];
// ... move the rows.
[self.personTableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];
// ... and update source so it is in sync with UI changes.
sourceIndexPath = indexPath;
}
break;
}
default: {
// Clean up.
UITableViewCell *cell = [self.personTableView cellForRowAtIndexPath:sourceIndexPath];
[UIView animateWithDuration:0.25 animations:^{
snapshot.center = cell.center;
snapshot.transform = CGAffineTransformIdentity;
snapshot.alpha = 0.1;
cell.detailTextLabel.alpha = 1;
cell.textLabel.alpha = 1;
} completion:^(BOOL finished) {
[snapshot removeFromSuperview];
snapshot = nil;
cell.hidden = NO;
}];
sourceIndexPath = nil;
break;
}
}
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
- (UIView *)customSnapshotFromView:(UIView *)inputView {
UIView *snapshot = [inputView snapshotViewAfterScreenUpdates:YES];
snapshot.alpha = 0.1;
snapshot.layer.masksToBounds = NO;
snapshot.layer.cornerRadius = 0.0;
snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
snapshot.layer.shadowRadius = 5.0;
snapshot.layer.shadowOpacity = 0.4;
return snapshot;
}
When I set the delegate to self like this:
longPress.delegate = self;
The able view scrolls, but then my selected cell doesn't move. What am I missing to make this work?
* Updated *
After doing some more reading/research I think in order for me to achieve the effect I want (the scrolling effect on the TableView in Apple's weather app) I think that my long press gesture will also have to handle the scrolling of my table view. The default scrolling starts to scroll the entire table instantly, where as I need the table to scroll only when the long pressed cell is at the top or the bottom of my TableView. Am I correct in thinking like this? I've been trying to find an example to break down and study, but haven't had any luck finding anything like that.
** Updated **
So I'm trying to figure out how to trigger the scroll up timer when the user drags a cell up towards the top. The problem I'm having right now is figuring out when that cell is close to the top, when its at the very top of the tableview, thats easy I could use something like tableViewHight + 100, but this code wont work when the tableview is scrolled down. Here is what I have so far:
NSLog(#"This is table view hight %.2f", tableViewHight);
NSLog(#"This is content offset %f", (personTableView.contentOffset.y));
NSLog(#"Should be 100 place holder %.2f", (tableViewHight - tableViewHight) + personTableView.contentOffset.y + 100);
NSLog(#"location y %f", location.y);
// gets called repeatedly
// Step 1: check to see if we need to start scrolling
if (location.y < tableViewHight - tableViewHight + 100) {
// ** top **
// Step 2: make sure the current y postoin isn't greater then the previous y postion
if (location. y <= originalLocation.y) {
// NSLog(#"This is the offset y %f", self.personTableView.contentOffset.y);
// Step 4: check to see if we have a timer and if not create one
[self startTimer];
}
else{
//Step 3: they started to scroll up so end the timer
[self endTimer];
}
}
else if(location.y > tableViewHight - 100)
{
// ** bottom **
// Step 2: make sure the current y postoin isn't less then the previous y postion
if (location. y >= originalLocation.y) {
NSLog(#"its less then 0");
if (!timer) {
// Step 4: check to see if we have a timer and if not create one
[self startTimer];
}
}
else{
//Step 3: they started to scroll up so end the timer
[self endTimer];
}
}
else{
// ** middle **
// Step 2: check to see if we have a timer and if so destory it
[self endTimer];
}
Basically I want to trigger that if statement when the cell is less then 100px from the hight of the scrollable table view.
From the UILongPressGestureRecognizer you can get the current y position of the touch. From that you can calculate how close to the bottom or top of the UITableViewthe touch is. If you determine that it's close enough to begin scrolling, then start a repeating NSTimer that increments or decrements the contentOffset of your UITableView by 1 pixel, scrolling your table. Change how fast it scrolls by changing the timeInterval of the timer.
When the UILongPressGestureRecognizer ends, or if the y position of the touch moves outside of the scrolling zone, then invalidate your timer, which will stop the scrolling.
If you felt adventurous you could also increase the speed of the scrolling dynamically as the user gets closer to the edge of the UITableView by changing the timeInterval as the user moves their touch up or down, as that is generally how this type of functionality works.
Good luck!

Disabling NSView fade animation for NSView `setHidden:`

I am working on a project that has the concept of draggable controls, everything is working fine except that NSView seems to employ a fade in/out animation when calling setHidden:.
I have been able to work around the problem by changing the line session.animatesToStartingPositionsOnCancelOrFail = YES; to NO and implementing the image snapback myself with a custom animated NSWindow subclass. it looks great, but I know there must be an easier way.
I have tried:
using NSAnimationContext grouping with duration of 0 around the setHidden: calls
setting the view animations dictionary using various keys (alpha, hidden, isHidden) on the control and superview
overriding animationForKey: for both the control and its superview
I am not using CALayers and have even tried explicitly setting wantsLayer: to NO.
Does anybody know how to either disable this animation, or have a simpler solution then my animated NSWindow?
here is my stripped down altered code with the bare minimum to see what I'm talking about.
#implementation NSControl (DragControl)
- (NSDraggingSession*)beginDraggingSessionWithDraggingCell:(NSActionCell <NSDraggingSource> *)cell event:(NSEvent*) theEvent
{
NSImage* image = [self imageForCell:cell];
NSDraggingItem* di = [[NSDraggingItem alloc] initWithPasteboardWriter:image];
NSRect dragFrame = [self frameForCell:cell];
dragFrame.size = image.size;
[di setDraggingFrame:dragFrame contents:image];
NSArray* items = [NSArray arrayWithObject:di];
[self setHidden:YES];
return [self beginDraggingSessionWithItems:items event:theEvent source:cell];
}
- (NSRect)frameForCell:(NSCell*)cell
{
// override in multi-cell cubclasses!
return self.bounds;
}
- (NSImage*)imageForCell:(NSCell*)cell
{
return [self imageForCell:cell highlighted:[cell isHighlighted]];
}
- (NSImage*)imageForCell:(NSCell*)cell highlighted:(BOOL) highlight
{
// override in multicell cubclasses to just get an image of the dragged cell.
// for any single cell control we can just make sure that cell is the controls cell
if (cell == self.cell || cell == nil) { // nil signifies entire control
// basically a bitmap of the control
// NOTE: the cell is irrelevant when dealing with a single cell control
BOOL isHighlighted = [cell isHighlighted];
[cell setHighlighted:highlight];
NSRect cellFrame = [self frameForCell:cell];
// We COULD just draw the cell, to an NSImage, but button cells draw their content
// in a special way that would complicate that implementation (ex text alignment).
// subclasses that have multiple cells may wish to override this to only draw the cell
NSBitmapImageRep* rep = [self bitmapImageRepForCachingDisplayInRect:cellFrame];
NSImage* image = [[NSImage alloc] initWithSize:rep.size];
[self cacheDisplayInRect:cellFrame toBitmapImageRep:rep];
[image addRepresentation:rep];
// reset the original cell state
[cell setHighlighted:isHighlighted];
return image;
}
// cell doesnt belong to this control!
return nil;
}
#pragma mark NSDraggingDestination
- (void)draggingEnded:(id < NSDraggingInfo >)sender
{
[self setHidden:NO];
}
#end
#implementation NSActionCell (DragCell)
- (void)setControlView:(NSView *)view
{
// this is a bit of a hack, but the easiest way to make the control dragging work.
// force the control to accept image drags.
// the control will forward us the drag destination events via our DragControl category
[view registerForDraggedTypes:[NSImage imagePasteboardTypes]];
[super setControlView:view];
}
- (BOOL)trackMouse:(NSEvent *)theEvent inRect:(NSRect)cellFrame ofView:(NSView *)controlView untilMouseUp:(BOOL)untilMouseUp
{
BOOL result = NO;
NSPoint currentPoint = theEvent.locationInWindow;
BOOL done = NO;
BOOL trackContinously = [self startTrackingAt:currentPoint inView:controlView];
BOOL mouseIsUp = NO;
NSEvent *event = nil;
while (!done)
{
NSPoint lastPoint = currentPoint;
event = [NSApp nextEventMatchingMask:(NSLeftMouseUpMask|NSLeftMouseDraggedMask)
untilDate:[NSDate distantFuture]
inMode:NSEventTrackingRunLoopMode
dequeue:YES];
if (event)
{
currentPoint = event.locationInWindow;
// Send continueTracking.../stopTracking...
if (trackContinously)
{
if (![self continueTracking:lastPoint
at:currentPoint
inView:controlView])
{
done = YES;
[self stopTracking:lastPoint
at:currentPoint
inView:controlView
mouseIsUp:mouseIsUp];
}
if (self.isContinuous)
{
[NSApp sendAction:self.action
to:self.target
from:controlView];
}
}
mouseIsUp = (event.type == NSLeftMouseUp);
done = done || mouseIsUp;
if (untilMouseUp)
{
result = mouseIsUp;
} else {
// Check if the mouse left our cell rect
result = NSPointInRect([controlView
convertPoint:currentPoint
fromView:nil], cellFrame);
if (!result)
done = YES;
}
if (done && result && ![self isContinuous])
[NSApp sendAction:self.action
to:self.target
from:controlView];
else {
done = YES;
result = YES;
// this bit-o-magic executes on either a drag event or immidiately following timer expiration
// this initiates the control drag event using NSDragging protocols
NSControl* cv = (NSControl*)self.controlView;
NSDraggingSession* session = [cv beginDraggingSessionWithDraggingCell:self
event:theEvent];
// Note that you will get an ugly flash effect when the image returns if this is set to yes
// you can work around it by setting NO and faking the release by animating an NSWindowSubclass with the image as the content
// create the window in the drag ended method for NSDragOperationNone
// there is [probably a better and easier way around this behavior by playing with view animation properties.
session.animatesToStartingPositionsOnCancelOrFail = YES;
}
}
}
return result;
}
#pragma mark - NSDraggingSource Methods
- (NSDragOperation)draggingSession:(NSDraggingSession *)session sourceOperationMaskForDraggingContext:(NSDraggingContext)context
{
switch(context) {
case NSDraggingContextOutsideApplication:
return NSDragOperationNone;
break;
case NSDraggingContextWithinApplication:
default:
return NSDragOperationPrivate;
break;
}
}
- (void)draggingSession:(NSDraggingSession *)session endedAtPoint:(NSPoint)screenPoint operation:(NSDragOperation)operation
{
// now tell the control view the drag ended so it can do any cleanup it needs
// this is somewhat hackish
[self.controlView draggingEnded:nil];
}
#end
There must be a layer enabled somewhere in your view hierarchy, otherwise there wouldn't be a fade animation. Here is my way of disabling such animations:
#interface NoAnimationImageView : NSImageView
#end
#implementation NoAnimationImageView
+ (id)defaultAnimationForKey: (NSString *)key
{
return nil;
}
#end
The solution you already tried by setting the view animations dictionary should work. But not for the keys you mention but for the following. Use it somewhere before the animation is triggered the first time. If you have to do it on the window or view or both, I don't know.
NSMutableDictionary *animations = [NSMutableDictionary dictionaryWithDictionary:[[theViewOrTheWindow animator] animations];
[animations setObject:[NSNull null] forKey: NSAnimationTriggerOrderIn];
[animations setObject:[NSNull null] forKey: NSAnimationTriggerOrderOut];
[[theViewOrTheWindow animator] setAnimations:animations];
Or also just remove the keys if they are there (might not be the case as they are implicit / default):
NSMutableDictionary *animations = [NSMutableDictionary dictionaryWithDictionary:[[theViewOrTheWindow animator] animations];
[animations removeObjectForKey:NSAnimationTriggerOrderIn];
[animations removeObjectForKey:NSAnimationTriggerOrderOut];
[[theViewOrTheWindow animator] setAnimations:animations];
Ok. I figured out that the animation I'm seeing is not the control, the superview, nor the control's window. It appears that animatesToStartingPositionsOnCancelOrFail causes NSDraggingSession to create a window (observed with QuartzDebug) and put the drag image in it and it is this window that animates back to the origin and fades out before the setHidden: call is executed (i.e. before the drag operation is concluded).
Unfortunately, the window that it creates is not an NSWindow so creating a category on NSWindow doesn't disable the fade animation.
Secondly, there is no public way that I know of to get a handle on the window, so I can't attempt directly manipulating the window instance.
It looks like maybe my workaround is the best way to do this, after all its not far from what AppKit does for you anyway.
If anybody knows how to get a handle on this window, or what class it is I would be interested to know.

Can't access a UIWebView apparently coming from storyboard

There's a view with one UIWebview in Portrait and two smaller UIWebViews in landscape - In landscape the two views represent the pages of a book and there's some pageview stuff going on. I can not determine where the second UIWebView is coming from. When the superview is loaded in landscape I can only access one of the the view on the left. The view on the right displays perfectly with the correct data, but I can't access it from the code until something causes the screen to redraw such as the page being "turned" or the orientation changing. Does this sound familiar to anyone?
Also, my NSLog function isn't working anymore and I have no idea where to click to make it come back. Please help.
Edit
Here's some code
// this is the function which is not accessing the view.
-(void) setCurrentTextSize:(int)cts {
for(int pageViewIndex = 0; pageViewIndex < [arrayOfReaderViewControllers count]; pageViewIndex++) {
readerViewController *r = [self arrayOfReaderViewControllers:pageViewIndex];
[r setCurrentTextSize:cts];
[r webViewDidFinishLoad:r.webView];
}
}
//this function populates arrayOfReaderViewControllers
-(void)initializeArrayOfReaderViewControllers {
readerViewController *vcLeft;
if([self.delegate isFirstLoad]) {
//we don't care what happens here 'cause it's not being called.
} else {
vcLeft = [readerViewController new];
if ( lastPageNumber > currentPageNumber) {
currentPageNumber = lastPageNumber;
[arrayOfReaderViewControllers replaceObjectAtIndex:0 withObject:[self jumpToPageVC:vcLeft]];
if(self.isLandscape) {
vcLeft = [arrayOfReaderViewControllers objectAtIndex:0];
[arrayOfReaderViewControllers replaceObjectAtIndex:1 withObject:[self getNextPageViewController:vcLeft]];
}
}
}
[self.delegate doMoreInitialization];
}

UIPageViewController black screen on iPad when loaded in landscape

I'm developing a UIPageViewController based app which works both on iPhone and iPad. With the iPhone there are no problems, since the spine location of the controller is always set to UIPageViewControllerSpineLocationMin. In the iPad however, I need to set the spine location to UIPageViewControllerSpineLocationMid when the device orientation is set to Landscape.
I have a strange issue only when i Load the controller in Landscape orientation, the following video will explain the situation..
YouTubeVideo
As you can see, everything works perfectly when i load the controller in portrait and also after i rotate the device when i load in landscape.
I really can't figure out where is the problem. Here is the code I use to load the controllers:
if (chapter.controllers) {
currentPage = [chapter bookPageForCharIndex:location];
//Load the correct controller for the bookmark page
NSArray *array = nil;
if (currentPage >= 0 && currentPage < chapter.controllers.count) {
if (UIDeviceOrientationIsLandscape([[UIDevice currentDevice]orientation]) && UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad) {
[self setDoubleSided:YES];
if (chapter.controllers.count > currentPage+1) {
array = [[NSArray alloc]initWithObjects:[chapter.controllers objectAtIndex:currentPage],[chapter.controllers objectAtIndex:currentPage+1],nil];
}
else {
array = [[NSArray alloc]initWithObjects:[chapter.controllers objectAtIndex:currentPage],[[[LSBookPageViewController alloc]init]autorelease],nil];
}
}
else {
array = [[NSArray alloc]initWithObjects:[chapter.controllers objectAtIndex:currentPage],nil];
}
}
else {
return;
}
[self playSoundsOfChapter:chapter];
if (isRestarting) {
[self setViewControllers:array
direction:UIPageViewControllerNavigationDirectionReverse
animated:YES
completion:nil];
isRestarting = NO;
}
else {
[self setViewControllers:array
direction:UIPageViewControllerNavigationDirectionForward
animated:YES
completion:nil];
}
[array release];
}
I think the error is in the first else clause. You should set a breakpoint after checking for device orientation and device, and step through the code. I would guess that your array comes back empty.

detect long press on UINavigationItem's back button

I want to add functionality to my back buttons through my UINavigationController-based app where long-pressing the back button will pop to root. However, I can't figure out where to attach the gesture recognizer. Do I subclass UINavigationBar and try and detect if the long press is in the left button region?
I've heard of people adding similar functionality before. Anyone have any ideas?
I know this question is old, but I came up with a solution. Instead of trying to add the gesture recognizer to the button itself (which would be ideal), I added it to the self.navigationController.navigationBar and then in the action method, use the locationInView to see if I'm over the back button. I wasn't entirely sure about how to identify the back button precisely, so I'm clumsily just grabbing the the first subview with an x coordinate less than some arbitrary value, but it seems promising. If someone has a better way to identify the frame of the back button, let me know.
- (void)longPress:(UILongPressGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateEnded)
{
// set a default rectangle in case we don't find the back button for some reason
CGRect rect = CGRectMake(0, 0, 100, 40);
// iterate through the subviews looking for something that looks like it might be the right location to be the back button
for (UIView *subview in self.navigationController.navigationBar.subviews)
{
if (subview.frame.origin.x < 30)
{
rect = subview.frame;
break;
}
}
// ok, let's get the point of the long press
CGPoint longPressPoint = [sender locationInView:self.navigationController.navigationBar];
// if the long press point in the rectangle then do whatever
if (CGRectContainsPoint(rect, longPressPoint))
[self doWhatever];
}
}
- (void)addLongPressGesture
{
if (NSClassFromString(#"UILongPressGestureRecognizer"))
{
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longPress:)];
[self.navigationController.navigationBar addGestureRecognizer:longPress];
[longPress release];
}
}
I believe UIGestureRecognizers can only be added to UIViews and subclasses of UIViews.
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html
The back button is a UIBarButtonItem that descends from NSObject. Therefore, you won't be able to attach a gesture recognizer to a standard back button using
UILongPressGestureRecognizer *longPressGesture =
[[[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(longPress:)] autorelease];
[self.navigationItem.backBarButtonItem addGestureRecognizer:longPressGesture];
You can however add a custom view to a UIBarButtonItem. A custom view could just as easily be a UIView, UIButton, UILabel, etc.
Example:
UIView *myTransparentGestureView = [[UIView alloc] initWithFrame:CGRectMake(0,0,40,30)];
[myTransparentGestureView addGestureRecognizer:longPressGesture];
[self.navigationItem.backBarButtonItem setCustomView:myTransparentGestureView];
// Or you could set it like this
// self.navigationItem.backBarButtonItem.customView = myTransparentGestureView;
[myTransparentGestureView release];
You have to be careful however, since setting properties on backBarButtonItem applies to the next view that you push. So if you have view A that pushes to view B and you want the gesture to be recognized when you tap back in view B. You must set it up in view A.
I followed a slightly different path, figured I'd share it. The above answers are fine, but really, if the long press is in the leading 1/3 of the nav bar, that's good enough for me:
- (void)longPress:(UILongPressGestureRecognizer *)gr
{
NSLog(#"longPress:");
UINavigationBar *navBar = [self navigationBar];
CGFloat height = navBar.bounds.size.height;
CGPoint pt = [gr locationOfTouch:0 inView:navBar];
//NSLog(#"PT=%# height=%f", NSStringFromCGPoint(pt), height);
if(CGRectContainsPoint(CGRectMake(0,0,100,height), pt)) {
[self popToViewController:self.viewControllers[0] animated:YES];
}
}
Here's my solution:
In appDelegate (the "owner" of the nav bar in my app), In applicationDidFinishLaunchingWithOptions:
Get the nav bar view and add the gesture recognizer to the whole view:
// Get the nav bar view
UINavigationBar *myNavBar = nil;
for (UIView *view in [self.window.rootViewController.view subviews]) {
if ([view isKindOfClass:[UINavigationBar class]]) {
NSLog(#"Found Nav Bar!!!");
myNavBar = (UINavigationBar *)view;
}
}
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self
action:#selector(backButtonLongPress:)];
[myNavBar addGestureRecognizer:longPress];
NSLog(#"Gesture Recognizer Added.");
Then in appDelegate, in -(void) backButtonLongPress:(id) sender
Check to see if the gesture occurs within the frame of the back button:
if ([sender state] == UIGestureRecognizerStateBegan) {
// Get the nav bar view
UINavigationBar *myNavBar = nil;
for (UIView *view in [self.window.rootViewController.view subviews]) {
if ([view isKindOfClass:[UINavigationBar class]]) {
NSLog(#"Found Nav Bar!!!");
myNavBar = (UINavigationBar *)view;
}
}
// Get the back button view
UIView *backButtonView = nil;
for (UIView *view in [myNavBar subviews]) {
if ([[[view class] description] isEqualToString:#"UINavigationItemButtonView"]) {
backButtonView = view;
NSLog(#"Found It: %#", backButtonView);
NSLog(#"Back Button View Frame: %f, %f; %f, %f", backButtonView.frame.origin.x, backButtonView.frame.origin.y, backButtonView.frame.size.width, backButtonView.frame.size.height);
}
}
CGPoint longPressPoint = [sender locationInView:myNavBar];
NSLog(#"Touch is in back button: %#", CGRectContainsPoint(backButtonView.frame, longPressPoint) ? #"YES" : #"NO");
if (CGRectContainsPoint(backButtonView.frame, longPressPoint)) {
// Place your action here
}
// Do nothing if outside the back button frame
}