使用iOS 17“弹出式”UIButton,如何在代码中设置所选项目?

问题描述 投票:0回答:1

假设你有一个弹出式按钮,

@IBOutlet var popupButton: UIButton!
let xx = ["Horse","Dog","Cat","Budgie"]
let opts = xx.map({ fn in
    return UIAction(title: fn) { [weak self] _ in
        self?. ...
    }
})
opts[2].state = .on
popupButton.menu = UIMenu(children: opts)

在构建过程中,您可以按照所示的方式设置所选项目,尽管这有点做作。

在应用程序运行期间,您到底如何从代码中更改所选项目?

不幸的是,我知道如何使用这样的扩展的唯一方法,这很难优雅:

// Don't do this. See solution found later in the answer
let temp: [UIAction] = thePopupButton.menu!.children as! [UIAction]
temp[3].state = .on
thePopupButton.menu = UIMenu(children: temp)
// Don't do this. See solution found later in the answer

确实有某种方法可以更改弹出 UIButton 上的所选项目吗?有谁知道吗

请注意,这个问题与操作表或警报控制器完全无关。如果您不熟悉新的 UIButton 可能性,请查看第一张图片。

ios swift uibutton uiaction
1个回答
0
投票

根据@sweeper 的提示,事实上这似乎确实有效。已测试:

extension UIButton {
    
    ///For the "popup" type buttons (iOS 14+), set the selected item.
    ///If the button is the wrong type or it's not possible, nothing is done.
    var forceSelectedIndex: Int {
        set {
            guard (self.menu != nil) else {
                return print("forceSelectedIndex impossible")
            }
            guard newValue > 0 && newValue < self.menu!.children.count else {
                return print("forceSelectedIndex impossible")
            }
            (self.menu!.children[newValue] as? UIAction)?.state = .on
        }
        get {
            return 0 // meaningless
        }
    }
}

没必要,我想这就是全部了。无需像我在问题中的示例那样复制。

© www.soinside.com 2019 - 2024. All rights reserved.