[英]Swift 3 UIPickerView programmatically start to spin
我正在使用Swift 3在iOS中創造某種命運。我使用了帶有UIPickerView的庫,我自定義了視圖,使行無休止(因此,用戶認為他可以滾動查看無休止的項目)。
唯一的問題是用戶可以通過命運之輪緩慢地滑動價格,因此基本上他可以選擇自己想要的任何價格。
盡管要防止這種情況發生,但是無論何時用戶點擊或滑動方向盤,我都會使UIPickerView旋轉,並使用一個隨機數來確定命運之輪的結果。
我知道如何向方向盤添加手勢識別器,但是我唯一不知道的是如何以編程方式啟動UIPickerView。
提前致謝!
我認為您正在尋找:
pick.selectRow(10, inComponent: 0, animated: true)
但是,如果您想查看完整的示例,我為您做了。
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])"
}
}
希望對你有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.