I have a ballon view and when I tap on cell UIMenuController doesn't appear. I tried to implement in
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath,
then I added a long press gesture
(void)longPress:(UILongPressGestureRecognizer *)recognizer,
in the end I added an implementation in extended
UITableViewCell
class, but it still doesn't work.
Here is an example
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (BOOL) canPerformAction:(SEL)selector withSender:(id) sender
{
return YES;
}
-(void)copyAction:(id)sender{
NSLog(#"copy");
}
-(void)deleteAction:(id)sender{
NSLog(#"delete");
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
BalloonCell *cell = (BalloonCell*)[tableView cellForRowAtIndexPath:indexPath];
[self becomeFirstResponder];
BOOL isCanBecomde = [self canBecomeFirstResponder];
BOOL isFirst = [self isFirstResponder];
UIMenuItem *copy = [[UIMenuItem alloc] initWithTitle:#"Копировать" action:#selector(copyAction:)];
UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:#"Удалить" action:#selector(deleteAction:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
CGRect drawRect = [cell convertRect:cell.bounds toView:self.view];
[menu setTargetRect:drawRect inView:window];
[menu setMenuItems:[NSArray arrayWithObjects:copy, delete, nil]];
[menu setMenuVisible:YES animated:YES];
}
Do you have any guess why UIMenuController doesn't appear?
Related
In an IOS app, I want to display a UIMenuController when longpressing an UIView located in UITableViewCell.
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
myTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell==nil)
{
cell=(myTableViewCell*)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
myView=<initMyView>
[cell.contentView addSubview:myView];
UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longTapGestureCapturedOnView:)];
longTap.minimumPressDuration=0.5f;
[myView addGestureRecognizer:longTap];
return cell;
}
- (void)longTapGestureCapturedOnView:(UITapGestureRecognizer *)gesture
{
items=[[NSMutableArray alloc]init];
if (gesture.state == UIGestureRecognizerStateBegan)
{
[items addObject:[[UIMenuItem alloc] initWithTitle:#"Copy" action:#selector(myCopy:)]];
[items addObject:[[UIMenuItem alloc] initWithTitle:#"Custom" action:#selector(myCustom:)]];
}
[[UIMenuController sharedMenuController] setMenuItems:items];
[[UIMenuController sharedMenuController] update];
[[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
BOOL result = NO;
if(#selector(myCopy:) == action ||#selector(myCustom:) == action ) {
result = YES;
}
return result;
}
The longTapGestureCapturedOnView is called, as well as the canPerformAction which is returning YES in the 2 cases, but no menuitem appears on the screen. What could I have done wrong ?
You also need
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
return YES ;
}
//
also it's not right to add gestures in cellForRowAt as it's being called upon scroll & cellReusing so add it in awakeFormNib method of UITableViewCell custom class
I am displaying custom UIMenuController in my tableview like this
but issue is that it is displaying in the center I want to display it on top of label which is orange colored. For displaying on top of label I did this [menu setTargetRect:CGRectMake(10, 10, 0, 0) inView:self.lbl]; below is the entire code.
But if I am displaying the UIMenuController without UITableView setTargetRect works fine.
Why setTargetRect is not working with UITableView?
setTargetRect Doc says:
(a) This target rectangle (targetRect) is usually the bounding rectangle
of a selection. UIMenuController positions the editing menu above this
rectangle; if there is not enough space for the menu there, it
positions it below the rectangle. The menu’s pointer is placed at the
center of the top or bottom of the target rectangle as appropriate.
(b) Note that if you make the width or height of the target rectangle
zero, UIMenuController treats the target area as a line or point for
positioning (for example, an insertion caret or a single point).
(c) Once it is set, the target rectangle does not track the view; if the
view moves (such as would happen in a scroll view), you must update
the target rectangle accordingly.
What I am missing?
MyViewController
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TheCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cid" forIndexPath:indexPath];
cell.lbl.text = [NSString stringWithFormat:#"%ld", (long)indexPath.row];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
return YES;
}
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
// required
}
MyCustomCell
- (void)awakeFromNib {
// Initialization code
UIMenuItem *testMenuItem = [[UIMenuItem alloc] initWithTitle:#"Test" action:#selector(test:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems: #[testMenuItem]];
[menu setTargetRect:CGRectMake(10, 10, 0, 0) inView:self.lbl];
[menu update];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(BOOL) canPerformAction:(SEL)action withSender:(id)sender {
return (action == #selector(copy:) || action == #selector(test:));
}
/// this methods will be called for the cell menu items
-(void) test: (id) sender {
NSLog(#"test");
}
-(void) copy:(id)sender {
UIMenuController *m = sender;
NSLog(#"copy");
}
1) First, please do this in your view controller's viewDidLoad method.
UIMenuItem *testMenuItem = [[UIMenuItem alloc] initWithTitle:#"Test"
action:#selector(test:)];
[[UIMenuController sharedMenuController] setMenuItems: #[testMenuItem]];
[[UIMenuController sharedMenuController] update];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(menuControllerWillShow:) name:UIMenuControllerWillShowMenuNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(menuControllerWillHide:) name:UIMenuControllerWillHideMenuNotification object:nil];
2) Then, add these two Methods. and set menuFrame inView to your cell
-(void)menuControllerWillShow:(NSNotification *)notification{
//Remove Will Show Notification to prevent
// "menuControllerWillShow" function to be called multiple times
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIMenuControllerWillShowMenuNotification object:nil];
//Hide the Original Menu View
UIMenuController* menuController = [UIMenuController sharedMenuController];
CGSize size = menuController.menuFrame.size;
CGRect menuFrame;
menuFrame.origin.x = self.tableView.frame.origin.x;
menuFrame.size = size;
[menuController setMenuVisible:NO animated:NO];
//Modify its target rect and show it again to prevent glitchy appearance
[menuController setTargetRect:menuFrame inView:cell];
[menuController setMenuVisible:YES animated:YES];
}
-(void)menuControllerWillHide:(NSNotification *)notification{
//re-register menuControllerWillShow
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(menuControllerWillShow:)
name:UIMenuControllerWillShowMenuNotification object:nil];
}
3) Implement tableView Delegates and implement these methods.
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
cell = (TableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
return YES;
}
-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
return NO;
}
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
// required
}
4) Setup the cells (subclassing UITableViewCell) with
-(BOOL) canPerformAction:(SEL)action withSender:(id)sender {
return (action == #selector(copy:) || action == #selector(test:)); } /// this methods will be called for the cell menu items
-(void) test: (id) sender {
NSLog(#"test"); }
-(void) copy:(id)sender {
NSLog(#"copy"); }
i am trying to use UIMenuController to perform a custom action on the table cell, from which the UIMenuController triggered by long time press.
I registered UILongPressGestureRecognizer in the viewDidLoad method in my subclass of UITableViewController and added custom item with #selector(handleMyAction).
- (void)viewDidLoad
{
[super viewDidLoad];
[self.refreshControl addTarget:self action:#selector(refreshView:) forControlEvents:UIControlEventValueChanged];
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(handleLongPress:)];
longPressGesture.minimumPressDuration = .5;
longPressGesture.delegate = self;
[self.tableView addGestureRecognizer:longPressGesture];
}
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if(gestureRecognizer.state == UIGestureRecognizerStateBegan)
{
CGPoint point = [gestureRecognizer locationInView:self.tableView];
NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];
if(indexPath == nil) return ;
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
UIMenuItem *it = [[UIMenuItem alloc] initWithTitle:#"My Action on this cell" action:#selector(handleMyAction:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:it, nil]];
[menu setTargetRect:cell.frame inView:cell.superview];
[menu setMenuVisible:YES animated:YES];
[self becomeFirstResponder];
}
}
I also override the
- (BOOL)canBecomeFirstResponder{
return YES;
}
When I press on one cell the context menu with the custom entry displays properly. BUT, the problem is how can I implement the method to handle the custom action, which should be performed on the tapped cell.
- (void)handleMyAction:(id)sender
{
NSLog(#"Action triggered, however need some way to refer the tapped cell");
}
Because the only information i can get in this method is the sender, which is the UIMenuController self, but i have no idea how can get the cell, on which the Menu triggered, so i can do further action regarding the cell itself.
Could some one help me on that?
Thanks.
Hai
Well you're currently adding the UIGestureRecognizer to the tableview itself. Why not add it to each cell instead (in cellForRowAtIndexPath when they are setup) ?
Thanks valheru. I find a "nice" approach to achieve that:)
Step one: In MyTableViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(handleLongPress:)];
longPressGesture.minimumPressDuration = .5;
longPressGesture.delegate = self;
[self.view addGestureRecognizer:longPressGesture];
}
which register the gesture recognizer of the long press on the table view controller.
- (BOOL)canBecomeFirstResponder
{
return YES;
}
which allows MyTableViewController response the long press and popup the context menu.
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if(gestureRecognizer.state == UIGestureRecognizerStateBegan)
{
CGPoint point = [gestureRecognizer locationInView:self.tableView];
NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];
if(indexPath == nil) return ;
MyCell *cell = (MyCell *)[self.tableView cellForRowAtIndexPath:indexPath];
UIMenuItem *determine = [[UIMenuItem alloc] initWithTitle:#"My Action on this cell" action:#selector(handleMyAction:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:determine, nil]];
[menu setTargetRect:cell.frame inView:cell.superview];
[menu setMenuVisible:YES animated:YES];
[cell becomeFirstResponder]; //here set the cell as the responder of the menu action
cell.delegate = self;// this is optional, if you don't want to implement logic in cell class
}
}
create the UIMenuController and popup when i long press the cell.
-(void)handleMyAction: (UITableViewCell *)cell
{
NSLog(#"%#", cell);
}
this function will be called later from the cell which is pressed.
Step two: Create a subclass of UITableViewCell named MyCell
In MyCell.h defines the table view controller the cell belongs as the delegate of the cell. And the callback function when the menu entry clicked
#property (nonatomic, strong) MyTableViewController *delegate;
-(void)handleMyAction:(id)sender;
in MyCell.m
- (BOOL)canBecomeFirstResponder
{
return YES;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if(action == #selector(handleMyAction:))
{
return YES;
}
return NO;
}
allows the MyCell to be the first responder and response the handleMyAction action by clicking on menu entry.
-(void)handleMyAction:(id)sender
{
[self.delegate handleMyAction:self]; //it's a coincidence both functions have the same name:)
}
this is the definition of the callback function, which will be called when click on the menu entry, and it in turn call the handMyAction function in the delegate of the cell (MyTableViewController, where the logic regarding the cell could be implemented.)
First declare a NSIndexPath type as a class variable.
#property (nonatomic, strong) NSIndexPath *savedIndexPathForThePressedCell;
Now in the Long press gesture recognizer function, get the TableViewCell using the recognizer view. Now save the IndexPath for the TableViewCell
- (void)longPressGestureFunction:(UILongPressGestureRecognizer *)recognizer
{
UITableViewCell *lTableViewCell = (UITableViewCell *)recognizer.view;
[lTableViewCell becomeFirstResponder];
/*Save the Indexpath of the cell pressed*/
self.savedIndexPathForThePressedCell = [mTableView indexPathForCell:lTableViewCell];
if (recognizer.state == UIGestureRecognizerStateBegan)
{
UIMenuItem *MenuDelete = [[UIMenuItem alloc] initWithTitle:#"Delete" action:#selector(Delete:)];
UIMenuItem *MenuForward = [[UIMenuItem alloc] initWithTitle:#"Forward" action:#selector(Forward:)];
UIMenuItem *MenuAddToContacts = [[UIMenuItem alloc] initWithTitle:#"Add To Contacts" action:#selector(addToContacts:)];
mSharedMenu = [UIMenuController sharedMenuController];
[mSharedMenu setMenuItems:[NSArray arrayWithObjects: MenuDelete, MenuForward, nil]];
[mSharedMenu setMenuVisible:YES animated:YES];
}
Now in the Menu selector method, select the row based on the saved indexPath.
- (void)Delete:(id)sender {
// NSLog(#"\n Delete Selected \n");
[mTableView setEditing:YES animated:YES];
[mTableView selectRowAtIndexPath:self.savedIndexPathForThePressedCell animated:YES scrollPosition:UITableViewScrollPositionNone];
}
I hope this helps!!!
I've implemented a long press gesture recognizer on a table view cell that shows the UIMenuController. But when menu shows, the corresponding table view cell deselects. Before showing the menu, I call, as required, [self becomeFirstResponder]. I think that this call deselects the cell, but how to make it to stay selected while the UIMenuController is visible?
In your UITableViewDelegate, override tableView:willDeselectRowAtIndexPath: and return nil when you don’t want your row to deselect, according to the documentation.
A simpler way of implementing this is using the specific UITableViewDelegate methods for dealing with UIMenuController.
But first, to make the cell stay selected, store the value of the cell presenting the menu in your class:
NSIndexPath *_editingIndexPath;
Then implement the UITableViewDelegateMethods:
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCustomTableViewCell *cell = (MyCustomTableViewCell *) [_tableView cellForRowAtIndexPath:indexPath];
_editingIndexPath = indexPath;
cell.showingMenu = YES;
return YES;
}
- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
if (action == #selector(copy:)) {
return YES;
}
return NO;
}
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
if (action == #selector(copy:))
{
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
if (cell && [cell isKindOfClass:[MessageConversationCell class]])
{
[UIPasteboard generalPasteboard].string = cell.textLabel.text;
}
}
}
The code above will take care of showing a "copy" menu on the cell after a long press.
Now, if you want the cell to stay selected while the menu is displayed:
Add a #property in your custom cell named "showingMenu" (note that this property was already set in the first block of code in this answer).
#property (nonatomic, assign) BOOL showingMenu;
Add (or modified if already present) the following method to your custom cell. This will take care of keeping the cell highlighted after the menu tried to unhighlight it (you may implement your own logic for highlighting a cell, in that case put it in the first branch of the if conditional):
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
if (_showingMenu)
{
[super setHighlighted:YES]
}
else
{
[super setHighlighted:highlighted];
}
}
Add an observer to be notified when the menu is going to be presented. This goes into the view controller, NOT in the custom cell:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didShowEditMenu:) name:UIMenuControllerDidShowMenuNotification object:nil];
Add on the view controller the method to be called when the menu is displayed:
- (void)didShowEditMenu:(NSNotification *)not {
[_tableView selectRowAtIndexPath:_editingIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
MyCustomTableViewCell *cell = (MyCustomTableViewCell*)[_conversationTableView cellForRowAtIndexPath:_editingIndexPath];
cell.showingMenu = NO;
}
And don't forget to remove the observer when no longer needed:
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerDidShowMenuNotification object:nil];
This will show a menu when a cell is long pressed, and keep the cell selected until the menu disappears, either because an option was chosen or because the user tapped somewhere else. It works pretty much like Whatsapp works when you select a message.
You say you are calling [self becomeFirstResponder] but your question does not indicate which object self is. I would guess self is your controller. You should be sending the becomeFirstResponder message to the UITableViewCell that is spawning the UIMenuController.
- (void)longPress:(UILongPressGestureRecognizer *)recognizer
{
if (recognizer.state == UIGestureRecognizerStateBegan)
{
TSTableViewCell *cell = (TSTableViewCell *)recognizer.view;
//This is your problem
[cell becomeFirstResponder];
UIMenuItem *flag = [[UIMenuItem alloc] initWithTitle:#"Flag" action:#selector(flag:)];
UIMenuItem *approve = [[UIMenuItem alloc] initWithTitle:#"Approve" action:#selector(approve:)];
UIMenuItem *deny = [[UIMenuItem alloc] initWithTitle:#"Deny" action:#selector(deny:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:flag, approve, deny, nil]];
[menu setTargetRect:cell.frame inView:cell.superview];
[menu setMenuVisible:YES animated:YES];
}
}
I have found this solution:
- (void)handleLongPress:(UILongPressGestureRecognizer *)longPressRecognizer
{
if (longPressRecognizer.state == UIGestureRecognizerStateBegan) {
UITableViewCell *cell = (UITableViewCell *)longPressRecognizer.view;
[cell setSelected:YES];
...
}
}
I have an application with a UITabBar. Every tab is a UINavigationController with several UIViewControllers inside. One of those View Controllers contains a UITableView, and I want to display a floating menu for deleting the long pressed UITableViewCell.
I am using UIMenuController but it's not displayed because the cell refuses to become first responder.
Here's my code:
- (void)viewDidLoad
{
[super viewDidLoad];
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.0; //second
[table addGestureRecognizer:lpgr];
[lpgr release];
}
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
CGPoint p = [gestureRecognizer locationInView: table];
NSIndexPath *indexPath = [table indexPathForRowAtPoint:p];
if (indexPath != nil) {
UITableViewCell* cell = [self tableView:table cellForRowAtIndexPath: indexPath];
[cell becomeFirstResponder];
UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:#"Delete" action:#selector(delete:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:delete, nil]];
[menu setTargetRect:cell.frame inView:cell.superview];
[menu setMenuVisible:YES animated:YES];
}
}
}
On the UITableViewCell I have overriden the method:
-(BOOL) canBecomeFirstResponder {
return YES;
}
Any ideas on why the cell is not becoming the first responder?
Thanks!
I think I fixed your code :-)
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
CGPoint p = [gestureRecognizer locationInView: self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
if (indexPath != nil) {
[self becomeFirstResponder];
UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:#"Delete" action:#selector(customDelete:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:delete, nil]];
[menu setTargetRect:[self.tableView rectForRowAtIndexPath:indexPath] inView:self.tableView];
[menu setMenuVisible:YES animated:YES];
}
}
}
- (void)customDelete:(id)sender {
//
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
if (action == #selector(customDelete:) ){
return YES;
}
return NO;
}
I did the following..
[self becomeFirstResponder];
[menu setTargetRect:[self.tableView rectForRowAtIndexPath:indexPath] inView:self.tableView];
Added true for canPerformAction Not mostly needed if you have implemented the function
Please change the tableview and other things to your local reference variables :-)
Good read - http://www.intridea.com/blog/2010/12/22/developers-notes-for-uimenucontroller