4

My app is in prototype stage of development. Some sliders do not have any action assigned to them either through storyboard or programmatically.

I need to display an alert when slider drag stops during testing. Can this be done through an extension of UISlider?

How can I assign a default action to UISlider when the drag ends to show an alert unless another action is assigned via interface builder or programmatically?

Similar Question

Cœur
  • 37,241
  • 25
  • 195
  • 267
nkirit
  • 379
  • 2
  • 4
  • 13

1 Answers1

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

Please check this modified Answer.

Md. Ibrahim Hassan
  • 5,359
  • 1
  • 25
  • 45