Wednesday, 14 December 2011

Touch/Tap Event on single Object in iPhone | Populate Custom MenuItems


#pragma mark TouchEvents
-(void) touchesBegan : (NSSet *)touches withEvent : (UIEvent *)event {

UITouch *touch = [[event allTouches]anyObject];

CGPoint touchLocation = [touch locationInView:self.view];
CGPoint origin = self.yourImgView.frame.origin;
CGFloat x2 = origin.x + self.yourImgView.frame.size.width;
CGFloat y2 = origin.y + self.yourImgView.frame.size.height;

/**
Touch Event only responds on Your ImageView
*/

if ((touchLocation.x >= origin.x && touchLocation.x <= x2) && (touchLocation.y >= origin.y && touchLocation.y <= y2))
    {

if ([touch tapCount] == 2) {

[self becomeFirstResponder];

/** Description
 * Create Custom UIMenu Item
 * If we want more Menuitems.So, we can take an array and selector on each items
 * setTargetRect : On which frame you want to tap and display menu item on it.
 * setMenuVisible: No Menu items to hide.
 * menuRect : Where you want to display menu items.
 */

UIMenuItem *menuPasteItem = [[UIMenuItem alloc] initWithTitle:@"Paste" action:@selector(YourMethodName1)];
UIMenuItem *menuCopyItem = [[UIMenuItem alloc] initWithTitle:@"Copy" action:@selector(YourMethodName2)];

UIMenuController *menuController = [UIMenuController sharedMenuController];

CGRect menuRect = CGRectMake(0,10,150,100);

[menuController setTargetRect:menuRect inView:self.yourImgView];
menuController.menuItems=[NSArray arrayWithObjects:menuPasteItem,menuCopyItem,nil];
[menuController setMenuVisible:YES animated:YES];

}


    }

}

#pragma mark BOOL operations

-(BOOL) canBecomeFirstResponder{

return YES;
}

-(BOOL) canPerformAction:(SEL)action withSender:(id)sender{

BOOL confirm = NO;

if (action == @selector(YourMethodName1))
confirm = YES;
if (action == @selector(YourMethodName2))
confirm = YES;

return confirm;

}


I love to write this post, it really helps for me.

Hope

No comments:

Post a Comment