在一个视图中设置两个UIPickerviews

时间:2015-12-04 01:45:44

标签: ios swift uipickerview

我遇到了问题在我的初学者Swift项目中,在一个视图中设置了两个UIPickerviews并且我一直收到Cannot subscript a value of type '[Range<Int>]'错误,我无法理解我的问题&#39我做错了。我正在研究这个项目,以便快速学习。

@IBOutlet weak var hourWorkedPicker: UIPickerView!
@IBOutlet weak var payRatePicker: UIPickerView!
@IBOutlet weak var total: UILabel!


let hoursWorked = [10...60]
let payRate = [9...50]

override func viewDidLoad() {
    super.viewDidLoad()
}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if pickerView == hourWorkedPicker {
        return hoursWorked.count
    } else { // if it's the second picker view
        return payRate.count
    }
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if pickerView == hourWorkedPicker {
        return hoursWorked[row] //ERORR IS HERE <-----------------------------
    } else {
        return payRate[row] //ERORR IS HERE <--------------------------------
    }
}

2 个答案:

答案 0 :(得分:0)

您的函数需要返回值为String。你没有将它们定义为字符串数组。

尝试使用

let hoursWorked = ["10", "20", "30", "40"];
let payRate = ["9", "10", "11"]

如果这需要付出很多努力,请以编程方式构建此数组。

答案 1 :(得分:0)

let hoursWorked = [10...60]
let payRate = [9...50]

这些是Range变量而不是数组。您只能对数组使用下标。因此它在

失败了
return hoursWorked[row]

因此,您应该将范围转换为数组。

要进行转换,您可以使用以下内容

let hoursWorked: [Int] = Array(10...60)
or
let hoursWorked = [Int](10...60)