以编程方式向上或向下滚动选择器视图

时间:2018-09-26 14:11:21

标签: ios swift uipickerview

如您在此处看到的,“ Picker View”上方的工具栏同时具有“ Next”和“ Back”按钮,当用户单击这些按钮时,我想以编程方式上下滚动“ Picker View”。我不知道该怎么做。请帮助我了解如何实现该功能。

enter image description here

1 个答案:

答案 0 :(得分:1)

您的<>按钮需要具有关联的操作,下面以“ selectNext”为例。我假设您只有一个组件:

var myElements: [SomeType] = // whatever elements you are displaying
var pickerView: UIPickerView // maybe an outlet or initialised programmatically

@objc func selectNext() {
    let currentSelectedRow = pickerView.selectedRow(inComponent: 0)
    guard curretSelectedRow < myElements.count else {
        return
    }
    if currentSelectedRow + 1 < myElements.count {
        pickerView.selectRow(currentSelectedRow + 1, inComponent: 0, animated: true)
    } else { // next element is 0th of list
        pickerView.selecteRow(0, inComponent: 0, animated: 0)
    }        
}

selectPrevious函数将遵循相同的用法。您还可以添加更多检查,以确保要选择的元素没有超出范围,或者myElements包含元素。