我试图找出为什么我的微调器不会保持整数。当我运行程序时,问号出现在微调器而不是1,2,3,4等等一直到100.我是Swift的新手,这是我第一次使用微调器/ Picker 。我的程序应该计算每加仑的里程数,但如果我不能让微调器工作,那就不会发生,哈哈。
以下是设置变量和微调器的代码:
class SecondViewController:
UIViewController,UIPickerViewDataSource,UIPickerViewDelegate
{
var BlopSoundURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Blop", ofType: "mp3")!)
var soundAudioPlayer = AVAudioPlayer()
var miles = 0.0
var gallonsUsed = 0.0
var mpg = 0.0
// Variables for slider
var minMiles = 1
var maxMiles = 1000
@IBOutlet weak var milesDrivenLabel: UILabel!
@IBAction func milesDrivenSlider(sender: UISlider)
{
}
@IBOutlet weak var gallonsUsedPicker: UIPickerView!
let pickerData = [1,2,3,4,5,6,7,8,9,10,11,
12,13,14,15,16,17,18,19,20,21,
22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,
42,43,44,45,46,47,48,49,50,51,
52,53,54,55,56,57,58,59,60,61,
62,63,64,65,66,67,68,69,70,71,
72,73,74,75,76,77,78,79,80,81,
82,83,84,85,86,87,88,89,90,91,
92,93,94,95,96,97,98,99,100]
还没有提交按钮的代码,但这里是微调器和程序的其余代码:
@IBAction func submitButton(sender: UIButton)
{
soundAudioPlayer.play()
let row = gallonsUsedPicker.selectedRowInComponent(0)
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return pickerData.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> Int!
{
return pickerData[row]
}
override func viewDidLoad()
{
super.viewDidLoad()
gallonsUsedPicker.dataSource = self
gallonsUsedPicker.delegate = self
soundAudioPlayer = AVAudioPlayer(contentsOfURL: BlopSoundURL, error: nil)
// Do any additional setup after loading the view, typically from a nib.
} // End of viewDidLoad
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} // End of didReceiveMemoryWarning
} // End of SecondViewController
我真的不确定函数中的代码是什么,因为这本书没有很好地解释它。然后,我将不得不弄清楚如何从微调器中取出数字并将其存储在变量中,以便我可以进行mpg计算。我知道如何使用滑块,但不是旋转器。它基本上是一回事吗?我觉得这会变得有趣。谢谢,非常感谢您的帮助。
答案 0 :(得分:1)
首先通过Swift约定,你应该用小写字母命名你的变量,并使用URLForResource(withExtension :)方法找出本地资源的URL:
let blopSoundURL = NSBundle.mainBundle().URLForResource("Blop", withExtension: "mp3")!
其次,选择器值应为String:
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return "\(row+1)"
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 100
}
你可以使用
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// do whatever with row+1 here
}
// or
@IBAction func submitButton(sender: UIButton) {
soundAudioPlayer.play()
let rowValue = gallonsUsedPicker.selectedRowInComponent(0) + 1
}