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

Ale*_*one 6 user-experience uibutton ios swift

我正在开发原型阶段的应用程序.某些界面元素没有通过故事板或以编程方式分配给它们的任何操作.

根据UX准则,我想在应用程序中找到这些"非活动"按钮,并在测试期间点击时显示"功能不可用"警报.这可以通过扩展UIButton来完成吗?

除非通过界面生成器或以编程方式分配其他操作,否则如何为UIButton分配默认操作以显示警报?

Md.*_*san 7

那么你想要实现的目标是什么.我已经使用UIViewController扩展并添加了一个闭包作为没有目标的按钮的目标.如果按钮没有动作,则会显示警报.

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

我测试了它.希望这可以帮助.快乐的编码.