【问题标题】:Assign Default Action to all UISlider programmatically以编程方式将默认操作分配给所有 UISlider
【发布时间】:2018-04-16 23:06:52
【问题描述】:

我的应用处于原型开发阶段。一些滑块没有通过情节提要或以编程方式分配给它们的任何操作。

我需要在测试期间停止拖动滑块时显示警报。这可以通过UISlider的扩展来完成吗?

除非通过界面构建​​器或以编程方式分配另一个操作,否则我如何在拖动结束时为 UISlider 分配默认操作以显示警报?

Similar Question

【问题讨论】:

  • 它对你有用吗?
  • 是的,它工作得很好。谢谢:)

标签: ios uislider swift4 uicontrol


【解决方案1】:
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)

}

}

extension UIViewController{
    func checkButtonAction(){
        for view in self.view.subviews as [UIView] {
            if let btn = view as? UISlider {
                if (btn.allTargets.isEmpty){
                    btn.add(for: .allTouchEvents, {
                        if (!btn.isTracking){
                            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)
    }
}

请检查此修改后的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多