Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UIMenuItem not working on PDFKit's PDFView

I'm trying to add a custom UIMenuItem to my PDFView

Here's what I'm doing in my sample Xcode project

#import <PDFKit/PDFKit.h>
#import <objc/runtime.h>

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic) PDFDocument *document;
@property(nonatomic) PDFView *pdfView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.

  NSURL *pdfPath = [[NSBundle mainBundle] URLForResource:@"pdf" withExtension:@"pdf"];

  _document = [[PDFDocument alloc] initWithURL:pdfPath];
  _pdfView = [[PDFView alloc] initWithFrame:CGRectZero];
  _pdfView.document = _document;

  [self.view addSubview:_pdfView];

  _pdfView.translatesAutoresizingMaskIntoConstraints = NO;
  [_pdfView.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
  [_pdfView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor].active = YES;
  [_pdfView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor].active = YES;
  [_pdfView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor].active = YES;

  UIMenuItem *menuItem =
  [[UIMenuItem alloc] initWithTitle:@"Custom Action"
                             action:@selector(doSomething)];
  [[UIMenuController sharedMenuController] setMenuItems:@[ menuItem ]];
  [[UIMenuController sharedMenuController] update];
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  if (sel_isEqual(action, @selector(doSomething))) {
    return YES;
  }
  return NO;
}

- (void)viewDidAppear:(BOOL)animated {
  [self becomeFirstResponder];
}

- (void)doSomething {
  NSLog(@"In Do Something!");
}

- (BOOL)canBecomeFirstResponder {
  return YES;
}

@end

This works fine on iOS 11 and 12, but on iOS 13, the UIMenuItem is not showing up

like image 401
HotBread Avatar asked Nov 06 '22 14:11

HotBread


1 Answers

For me assigning menuItems in handler of NSNotification.Name.PDFViewSelectionChanged works

NotificationCenter.default.addObserver(self,
                                       selector: #selector(selectionChangeNotification),
                                       name: NSNotification.Name.PDFViewSelectionChanged,
                                       object: pdfView)


@objc
private func selectionChangeNotification() {
    let menuItem = UIMenuItem(title: "Custom Action", action: #selector(doSomething))
    UIMenuController.shared.menuItems = [menuItem]
}
like image 117
Igor Palaguta Avatar answered Nov 13 '22 15:11

Igor Palaguta