微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)
    }
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐