gpt4 book ai didi

ios - UIPickerView - 循环数据

转载 作者:IT王子 更新时间:2023-10-29 05:21:30 25 4
gpt4 key购买 nike

我目前正在使用 Swift 开发一个应用程序,其中我使用了 UIPickerView,请参见下面的图像。当前,当用户滚动到最后一个数据时,UIPickerView 会停止,但我希望它永远不会停止。我希望当您处于底部时,只需继续滚动,就可以从第一个数据开始。或者在顶部时向上滚动。我希望它像 Apple 的倒计时一样,您可以随时向上或向下拖动。

我想要的样子:

enter image description here

目前情况:

enter image description here

最佳答案

这里有四个步骤——我们将设置一些常量来保存选择器 View 数据和一些配置,然后我们将添加 UIPickerViewDataSourceUIPickerViewDelegate 方法,我们将以 viewDidLoad 初始化结束。

首先是配置:

private let pickerViewData = Array(0...59)     // contents will be 0, 1, 2, 3...59, change to whatever you want
private let pickerViewRows = 10_000 // any big number
private let pickerViewMiddle = ((pickerViewRows / pickerViewData.count) / 2) * pickerViewData.count

请注意 pickerViewMiddle 常量——它经过计算可以很容易地从行偏移中获取我们的当前值。关于数据源——我们实际上只需要为每一行提供一个标题,但我们将添加一个辅助方法来将行号转换为数组中的值:

extension ViewController : UIPickerViewDataSource {
func valueForRow(row: Int) -> Int {
// the rows repeat every `pickerViewData.count` items
return pickerViewData[row % pickerViewData.count]
}

func rowForValue(value: Int) -> Int? {
if let valueIndex = find(pickerViewData, value) {
return pickerViewMiddle + value
}
return nil
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return "\(valueForRow(row))"
}
}

最后我们将设置委托(delegate):

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

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerViewRows
}

// whenever the picker view comes to rest, we'll jump back to
// the row with the current value that is closest to the middle
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let newRow = pickerViewMiddle + (row % pickerViewData.count)
pickerView.selectRow(newRow, inComponent: 0, animated: false)
println("Resetting row to \(newRow)")
}

}

要初始化,请在您的 viewDidLoad 中设置委托(delegate)和数据源,然后移动到选择器中间的正确行:

self.picker.delegate = self
self.picker.dataSource = self
let initialValue = 0
if let row = rowForValue(initialValue) {
self.picker.selectRow(row, inComponent: 0, animated: false)
}
// or if you just want to start in the middle:
// self.picker.selectRow(pickerViewMiddle, inComponent: 0, animated: false)

关于ios - UIPickerView - 循环数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26063039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com