我的应用程序中有一个UIMenu,我正在以特定的顺序填充它.我希望菜单始终以我填充它的顺序显示.
然而,UIMenu的自动行为会以此顺序显示菜单,并将其作为"优先"顺序.这意味着,它有时会更改列表的顺序,以将第一项(最高优先级)放置在离打开菜单的按钮最近的位置.
因此,在这种默认行为下,我看到我的列表有时会以相反的顺序显示.
我知道UIConextMenu有一个.Fixed选项,该选项可以使用meny.pererredMenuElementOrder进行设置.然而,我没有看到Uimenu有任何类似的东西.
关于如何将菜单顺序设置为.修复或阻止此自动排序行为,您有什么建议吗?
下面的代码片段显示了我如何在一个定制的Textfield类中创建和填充我的菜单:
private var dropdownMenu = UIMenu() {
didSet {
dropdownButton.menu = dropdownMenu
}
}
/// configureDropdownMenu() is used to set the menu contents for your dropdown textfield.
/// - Parameter viewModel: Must set the data of your ViewModel in the View layer. The ViewModel data will be used to populate the dropdown menu.
func configureDropdownMenu(with viewModel: CustomPulldownTextFieldViewModel) {
// Set the field type and the delegate
self.customFieldType = viewModel.dropdownType
self.isEnabled = true
var dropdownOptions: [String: [UIAction]] = [:]
var dropdownChildren: [UIMenuElement] = []
switch viewModel.dropdownType {
case .categorized:
guard let dropdownHeaders = viewModel.pulldownHeaders else {
fatalError("\nFatal Error: Must pass in headers for categorized dropdown type\n")
}
for (index, section) in viewModel.sectionOptions.enumerated() {
let sectionHeader = dropdownHeaders[index]
dropdownOptions[sectionHeader] = section.map { title in
UIAction(title: title, state: .off) { [self] _ in
textField.text = title
self.delegate?.selectedOptionFromList(pulldownField: self, selection: title)
}
}
}
for header in dropdownHeaders {
// Check if the section is not empty before adding it
if let sectionActions = dropdownOptions[header], !sectionActions.isEmpty {
dropdownChildren.append(UIAction(title: header, attributes: [.disabled], state: .off, handler: { _ in }))
dropdownChildren.append(contentsOf: sectionActions)
}
}
let categorizedMenu = UIMenu(options: .singleSelection, children: dropdownChildren)
self.dropdownMenu = categorizedMenu
case .uncategorized:
// Uncategorized list MUST only have one section in sectionOptions
dropdownChildren = viewModel.sectionOptions[0].map { title in
UIAction(title: title, state: .off) { [self] _ in
textField.text = title
self.delegate?.selectedOptionFromList(pulldownField: self, selection: title)
}
}
let uncategorizedMenu = UIMenu(options: .displayInline, children: dropdownChildren)
self.dropdownMenu = uncategorizedMenu
case .none:
fatalError("\nFatal Error: Must set a dropdownType in the view model\n")
}
}