0

Is there any way to make a UIPickerView "spin" like for a lottery. I would like make an UIPickerView and a button. When the user press the button, I would like the UIPickerView to spin for a while, and then stop at a random place. Is that possible?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Lasse Bickmann
  • 195
  • 3
  • 14
  • You can have a look at this awesome library in order to animate your app. But you need a designer or some knowledge for After Effect animations. https://github.com/airbnb/lottie-ios –  Mar 29 '18 at 13:26
  • Possible duplicate of [How do I decrease the speed in which a row is selected in a PickerView?](https://stackoverflow.com/questions/43740187/how-do-i-decrease-the-speed-in-which-a-row-is-selected-in-a-pickerview) – J. Doe Mar 29 '18 at 14:22
  • finally I made images on top of each other with constraints, and animates the bottom constraint :) UIPickerView is not suitable for this – J. Doe Mar 29 '18 at 14:22

1 Answers1

1

I think you are looking for this:

pick.selectRow(10, inComponent: 0, animated: true)

But if you want to see a full example I made this for you.

class ViewController: UIViewController, UIPickerViewDataSource{

@IBOutlet var pick: UIPickerView!

var myArr = [Int]()

var myT = Timer()

override func viewDidLoad() {
    super.viewDidLoad()

    for element in 0...100 {

        myArr.append(element)
        }


    myT = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.movePicker), userInfo: nil, repeats: true)



}



 //MARK: - move picker

func movePicker()  {


    let position = Int(arc4random_uniform(89) + 10)


    pick.selectRow(position, inComponent: 0, animated: true)
    pick.showsSelectionIndicator = true

    if position == 50 || position == 72 || position == 90 || position == 35  {

        myT.invalidate()

        let alert = UIAlertController(title: "You Won!!", message: "Congratulations!!!", preferredStyle: .alert)
        let buttonOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
        let playAgain = UIAlertAction(title: "Play Again!", style: .default, handler: { (action) in

            self.myT = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.movePicker), userInfo: nil, repeats: true)
        })

        alert.addAction(buttonOK)
        alert.addAction(playAgain)

        present(alert, animated: true, completion: nil)



    }

}




 //MARK: - picker
func numberOfComponents(in pickerView: UIPickerView) -> Int {

    return 1

}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return myArr.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return "\( myArr[row])"
}


}

I hope it's helped you

Gowtham Sooryaraj
  • 3,639
  • 3
  • 13
  • 22