NSSharingService Sharing子菜单

时间:2012-09-11 22:03:41

标签: macos cocoa menu menuitem submenu

如何在Mac应用中添加“共享”子菜单?一个例子是Safari>文件>分享。我戳了Apple SharingServices sample code,但它没有包含工作菜单项。

enter image description here

现在我有一个按钮,在点按时显示可用的共享服务选择器:

NSMutableArray *shareItems = [NSMutableArray arrayWithObject:[self.noteSynopsisView string]];
NSSharingServicePicker *sharingServicePicker = [[NSSharingServicePicker alloc] initWithItems:shareItems];
sharingServicePicker.delegate = self;
[sharingServicePicker showRelativeToRect:[self.shareButton bounds] ofView:self.shareButton preferredEdge:NSMaxYEdge];

我还在MainWindow.xib的File菜单下定义了一个Share子菜单项。

据我了解,NSSharingService列表正在动态生成。所以我不能真正预定义我在Interface Builder中创建的菜单项的服务。

感谢您的帮助。

3 个答案:

答案 0 :(得分:15)

查看NSSharingService的+ sharingServicesForItems:。在-validateMenuItem:方法中,您可以使用它返回的NSSharingServices的-title和-image创建子菜单。将每个服务与每个菜单项相关联,并将每个菜单项的操作指向:

- (IBAction)shareFromService:(id)sender {
  [[sender representedObject] performWithItems: arrayOfItemsToShare];
}

这真的很简单。 Apple在这方面做得很好。

答案 1 :(得分:7)

我发现要点可以帮助您轻松创建适当服务的子菜单。 https://gist.github.com/eternalstorms/4132533

这是一个NSSharingServicePicker类别。

答案 2 :(得分:0)

Swift 版本:

extension NSSharingServicePicker {
    
    class func menu(forSharingItems items: [AnyHashable]) -> NSMenu? {
        
        let sharingServices = NSSharingService.sharingServices(forItems: items)
        
        if sharingServices.isEmpty {
            return nil
        }
        
        let menu = NSMenu()
        
        for service in sharingServices {
            
            let item = MenuItem(label: service.title, action: #selector(_openSharingService), target: self, userInfo: ["sharingItems": items])
            
            item.image = service.image
            item.representedObject = service
            item.target = self
            menu.addItem(item)
            
        }
        
        return menu
        
    }
    
    @objc class private func _openSharingService(sender: MenuItem) {
        
        guard let items = sender.userInfo["sharingItems"] as? [AnyHashable], let service = sender.representedObject as? NSSharingService else {
            return
        }
        
        service.perform(withItems: items)
        
    }
    
}

class MenuItem: NSMenuItem {
    
    var userInfo: [String : Any] = [:]
    
    init(label: String, action: Selector?, target: AnyObject?, userInfo: [String : Any]) {
        self.userInfo = userInfo
        super.init(title: label, action: action, keyEquivalent: "")
    }
    
    required init(coder decoder: NSCoder) {
        super.init(coder: decoder)
    }
    
}