自定义UIMenuItem在PDFKit的PDFView上不起作用

时间:2019-08-14 19:00:32

标签: ios objective-c ios13 ios-pdfkit apple-pdfkit

我正在尝试向我的UIMenuItem添加自定义PDFView

这就是我在示例Xcode项目中正在做的事情

#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

这在iOS 11和12上正常运行,但是在iOS 13上,UIMenuItem没有显示

1 个答案:

答案 0 :(得分:0)

对我来说,在menuItems处理程序中分配NSNotification.Name.PDFViewSelectionChanged有用

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]
}