swift UIBarButtonItem中的上下文菜单问题

omqzjyyz  于 2022-10-31  发布在  Swift
关注(0)|答案(1)|浏览(240)

我把UIBarButtonItem放在Toolbar中,就像你在Storyboard中看到的那样。我把UIMenu放在UIBarButtonItem.menu中。当我在UIMenu中单击一个按钮时,我所单击的按钮的图标被转移到UIBarButtonItem中。为什么会发生这种情况?

问题:
为什么当我从ContextMenu按下按钮时UIBarButtonItem的图标会改变?
视频:

情节提要:

用户界面栏按钮项属性:

视图控制器:

@IBOutlet weak var fooItem: UIBarButtonItem!

//MARK: Functions
override func viewDidLoad() {
    super.viewDidLoad()
    fooItem.menu = ContextMenuManager.shared.makeUIMenu()
}

上下文菜单管理器:

protocol ContextMenuFunctionable {
    func didTappedEmptyFolder()
    func didTappedImportFile()
}

class ContextMenuManager {

    static var shared = ContextMenuManager()

    var delegate: ContextMenuFunctionable?
    var emptyFolder: UIAction?
    var importFile: UIAction?
    var importPhotoOrVideo: UIAction?

    private init() {

        emptyFolder = UIAction(
            title: "Empty Folder",
            image: .folderBadgePlus
                .applyingSymbolConfiguration(.symbolConfig),
            identifier: nil,
            state: .off,
            handler: { _ in self.delegate?.didTappedEmptyFolder() }
        )

        importFile = UIAction(
            title: "Import File",
            image: .squareAndArrowDown.applyingSymbolConfiguration(.symbolConfig),
            identifier: nil,
            state: .off,
            handler: { _ in self.delegate?.didTappedImportFile() }
        )

        importPhotoOrVideo = UIAction(
            title: "Import Photo & Video",
            image: .photo.applyingSymbolConfiguration(.symbolConfig),
            identifier: nil,
            state: .off,
            handler: { _ in self.delegate?.didTappedImportFile() }
        )
    }

    func makeUIMenu() -> UIMenu {
        guard let emptyFolder, let importFile, let importPhotoOrVideo else { return UIMenu() }
        return UIMenu(title: "Add",
                      image: .folder.applyingSymbolConfiguration(.symbolConfig),
                      options: [.displayInline, .singleSelection],
               children: [importPhotoOrVideo, importFile, emptyFolder])
    }
}
b4qexyjb

b4qexyjb1#

取消选中“选择作为主要操作”复选框,按钮的图标在您进行菜单选择时应不再更改。
我复制了您在代码中看到的内容。我基本上使用您的ContextMenuManager代码创建了一个菜单,但我创建的UIBarButtonItem如下:

let menu = UIMenu(title: "Add",
                  options: [.displayInline, .singleSelection],
                  children: [importPhotoOrVideo, importFile, emptyFolder])

let button = UIBarButtonItem(image: UIImage(systemName: "doc.on.clipboard.fill"), menu: menu)
button.changesSelectionAsPrimaryAction = false

changesSelectionAsPrimaryAction设置为true时,按钮的图标反映所选菜单。当设置为false时,它保留自己的图标。

相关问题