Search code examples
swiftios8uipickerview

fade out date picker after 3 seconds without reaction


I have swift iOS8 code, which fades a date picker in.

  UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
            self.PickerView.alpha = 1.0
            }, completion: nil)

I want to fade it automaticaly out, if after 3 seconds the picker view has not changed. Is that possible?

I trie something like this:

        // Fade in
        UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
            self.PickerView.alpha = 1.0
            }, completion: { finished in
                sleep(3)
                UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
                    self.PickerView.alpha = 0.0
                    }, completion: nil)
        })

Problem is: I cant not change the value of the picker while sleep is active.


Solution

  • You will need to setup a timer that can be used for triggering when the picker will be faded out of view. You would invalidate this timer if/when the picker value changes:

    var timer: NSTimer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Fade the picker in
        UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
            self.PickerView.alpha = 1.0
        }) { (finished) -> Void in
    
            // Start the timer after the fade-in has finished
            self.startTimer()
    
        }
    }
    
    func startTimer() {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "fadeOutPicker", userInfo: nil, repeats: false)
    }
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    
        // Invalidate the timer when the picker value changes
        timer?.invalidate()
    
        // (Re)start the timer
        startTimer()
    }
    
    func fadeOutPicker() {
        // Fade the picker out
        UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
            self.PickerView.alpha = 0.0
        }, completion: nil)
    }
    

    If pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) is not being called you will need to become the delegate of the UIPickerView.

    As a side note, by convention your variables should not stat with an uppercase (i.e. self.PickerView should be self.pickerView).