gpt4 book ai didi

iOS Swift - 如何以编程方式为所有按钮分配默认操作

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:11 42 4
gpt4 key购买 nike

我正在开发一个处于原型(prototype)开发阶段的应用程序。某些界面元素没有通过 Storyboard 或编程方式分配给它们的任何操作。

根据 UX 指南,我想在应用程序中找到这些“非事件”按钮,并让它们在测试期间点击时显示“功能不可用”警报。这可以通过扩展 UIButton 来完成吗?

除非通过界面生成器或以编程方式分配另一个 Action ,否则如何将默认 Action 分配给 UIButton 以显示警报?

最佳答案

好吧,您想要实现的目标是可以实现的。我使用 UIViewController 扩展并添加一个闭包作为没有目标的按钮的目标来完成此操作。如果按钮没有 Action ,则会显示警报。

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
self.checkButtonAction()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

}
@IBAction func btn_Action(_ sender: UIButton) {

}

}

extension UIViewController{
func checkButtonAction(){
for view in self.view.subviews as [UIView] {
if let btn = view as? UIButton {
if (btn.allTargets.isEmpty){
btn.add(for: .touchUpInside, {
let alert = UIAlertController(title: "Test 3", message:"No selector", preferredStyle: UIAlertControllerStyle.alert)

// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

// show the alert
self.present(alert, animated: true, completion: nil)
})
}
}
}

}
}
class ClosureSleeve {
let closure: ()->()

init (_ closure: @escaping ()->()) {
self.closure = closure
}

@objc func invoke () {
closure()
}
}

extension UIControl {
func add (for controlEvents: UIControlEvents, _ closure: @escaping ()->()) {
let sleeve = ClosureSleeve(closure)
addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
objc_setAssociatedObject(self, String(format: "[%d]", arc4random()), sleeve, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}

我已经测试过了。希望这可以帮助。快乐编码。

关于iOS Swift - 如何以编程方式为所有按钮分配默认操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45160145/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com