Simple way to show the 'Copy' popup on UITableViewCells like the address book App

后端 未结 7 1391
渐次进展
渐次进展 2020-12-12 13:38

Is there a simple way for subclasses of UITableViewCell to show the \'Copy\' UIMenuController popup like in the Address book app (see screenshot), after the selection is hel

7条回答
  •  北海茫月
    2020-12-12 13:59

    Your UITableViewCell subclass may look like this

    @interface MenuTableViewCell : UITableViewCell {
    }
    - (IBAction)copy:(id)sender;
    - (void)showMenu;
    
    @end
    
    
    @implementation MenuTableViewCell
    
    - (BOOL)canBecomeFirstResponder {
        return YES;
    }
    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
    {
        if (action == @selector(copy:)) {
            return YES;
        }
        return NO;
    }
    - (IBAction)copy:(id)sender {
    }
    - (void)showMenu {
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
        [self becomeFirstResponder];
        [[UIMenuController sharedMenuController] update];
        [[UIMenuController sharedMenuController] setTargetRect:CGRectZero inView:self];
        [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
    
    }
    
    @end
    

    And the UITableView delegate methods are like

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        static NSString *CellIdentifier = @"Cell";
    
        MenuTableViewCell *cell = (MenuTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[MenuTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
    
        // Configure the cell.
        return cell;
    }
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        MenuTableViewCell *cell = (MenuTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell showMenu];
    }
    

提交回复
热议问题