获取当前 UIButton 菜单选中项

Getting the current UIButton menu selected item

我有一个带有菜单和多个操作的 uibutton。

每当用户 select 一个菜单项时,我想获取它并打印它。

这是我的按钮:

   private lazy var measurementField: UIButton = {
    let saveAction = { (action: UIAction) in
        //action
    }
    let saveMenu = UIMenu(children: [
        UIAction(title: Ingredient.Measurements.oz.rawValue, image: nil, handler: saveAction),
        UIAction(title: Ingredient.Measurements.grams.rawValue, image: nil, handler: saveAction),
        UIAction(title: Ingredient.Measurements.cups.rawValue, image: nil, handler: saveAction),
        UIAction(title: Ingredient.Measurements.tsp.rawValue, image: nil, handler: saveAction),
        UIAction(title: Ingredient.Measurements.tbsp.rawValue, image: nil, handler: saveAction),
        UIAction(title: Ingredient.Measurements.quarts.rawValue, image: nil, handler: saveAction),
        UIAction(title: Ingredient.Measurements.pints.rawValue, image: nil, handler: saveAction),
    ])
    var config = UIButton.Configuration.filled()
    config.baseBackgroundColor = .label
    let button = UIButton(configuration: config)
    button.menu = saveMenu
    button.showsMenuAsPrimaryAction = true
    button.changesSelectionAsPrimaryAction = true
    button.addTarget(CreateFormViewController(), action: #selector(CreateFormViewController.linkData), for: .touchUpInside)
    return button
}()

这是我的select或(应该触发的动作):

@objc public func linkData(..more params... , _ sender:UIButton?) { 
    ...
    print(sender?.menu?.title)
    ...
}

它只打印 'nil' 不过。 我怎样才能获取菜单 select 编辑的项目?

您可以将所选项目提取到操作块中

let saveAction = { (action: UIAction) in
    //action
    print(action.title)
}

UIMenu 没有 'selectedItem'。当您的操作方法 linkData 被调用时,您正在尝试打印菜单标题,而不是 UIAction 的标题。如果查看 UIMenu 的完整初始化程序,您会看到 UIMenu 初始化程序具有 'title' 属性,默认情况下设置为“”(空字符串)。

public convenience init(title: String = "", image: UIImage? = nil, identifier: UIMenu.Identifier? = nil, options: UIMenu.Options = [], children: [UIMenuElement] = [])

如果您想打印操作项的标题,则必须在处理程序闭包中执行此操作:

let saveAction = { (action: UIAction) in
  //do your stuff here
}

p.s。如果您想在控制器中引用自己或任何其他 class-object,请不要忘记将此引用捕获为 unowned/weak 以避免保留周期:

let saveAction = { [weak self] (action: UIAction) in
  self?.printActionItemTitle(action.title)
}