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

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

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

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

解决方法

那么你想要实现的目标是什么.我已经使用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)
    }
}

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...