【发布时间】:2019-12-05 18:50:43
【问题描述】:
我正在尝试为我的应用程序中的每个视图创建一个自定义菜单,但是在视图控制器中似乎没有调用 buildMenu。这是一个例子:
在我的 AppDelegate 中,使用了此代码,它 100% 正常工作。
override func buildMenu(with builder: UIMenuBuilder) {
print("Updating menu from AppDelegate")
super.buildMenu(with: builder)
let command = UIKeyCommand(
input: "W",
modifierFlags: [.command],
action: #selector(self.helloWorld(_:))
)
command.title = "Hello"
builder.insertChild(UIMenu(
__title: "World",
image: nil,
identifier: UIMenu.Identifier(rawValue: "com.hw.hello"),
options: [],
children: [command]
), atEndOfMenu: .file)
}
@objc private func helloWorld(_ sender: AppDelegate) {
print("Hello world")
}
但是我需要根据用户在应用程序中的位置更改菜单中可用的选项,因此我尝试在 UIViewController 中执行此操作:
override func viewDidAppear(_ animated:Bool){
// Tried all of these to see if any work
UIMenuSystem.main.setNeedsRebuild()
UIMenuSystem.context.setNeedsRebuild()
UIMenuSystem.main.setNeedsRevalidate()
UIMenuSystem.context.setNeedsRevalidate()
}
又一次……
// This is never called
override func buildMenu(with builder: UIMenuBuilder) {
print("Updating menu in View Controller")
}
但 UIViewController 中的 buildMenu 永远不会被调用 :(
如果这是预期行为或是否有任何解决方法,您有什么想法吗?
【问题讨论】:
-
不确定你要重建菜单做什么,但你可以在视图控制器中使用
validateCommand:方法来动态更新菜单选项(即禁用/启用命令或更改其标题)。
标签: ios ios13 mac-catalyst uimenu uimenubuilder