UIPickerView从中间的选定行开始

时间:2015-10-13 14:11:36

标签: string global-variables swift2 uipickerview xcode7

当用户从UIPickerView中选择状态时,会将他们带到另一个viewController,其中包含所选状态的数据。当他们点击“后退”按钮并转到viewController pickerView时,它始终从第一个状态开始,在这种情况下是亚利桑那州。如果这是他们最初选择的状态,我怎么能让它已经滚动到中间并选择田纳西州?我正在使用Xcode 7和Swift 2,谢谢!

我有UIPickerView从中获取数据:

let pickerData = ["Arizona", "Arkansas", "California","Tennessee", "Texas", "Utah", "Virginia"]

当用户选择pickerView中的状态时,它会获取该值并将其添加到变量中:

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    //Takes the selected state and adds it to the variable 'currentState'
    currentState = pickerData[row]
    savedStateGV = currentState
}

'savedStateGV'是全局变量,'currentState'是局部变量。两者都是String类型。

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) -> String? {
    return pickerData[row]
}

2 个答案:

答案 0 :(得分:2)

你可以在viewcontroller中定义一个属性middleOfPicker(一个整数),你可以使用代码序列在例程“viewDidLoad”中设置这个属性(yourpicker是你给你的选择器的IBOutlet名称):

middleOfPicker = pickerData.count / 2
yourpicker.selectRow = middleOfPicker

最后,你的“后退按钮”的动作例程应包括声明:

yourpicker.selectRow = middleOfPicker

答案 1 :(得分:0)

快速4

    yourpicker.selectRow(middleOfPicker, inComponent: 0, animated: true)