我可以以编程方式滚动到 UIPickerView 中所需的行吗?
Posted
技术标签:
【中文标题】我可以以编程方式滚动到 UIPickerView 中所需的行吗?【英文标题】:Can I programmatically scroll to a desired row in UIPickerView? 【发布时间】:2011-02-04 04:55:06 【问题描述】:默认情况下,在初始化 UIPickerView 后第一行会突出显示。如何以编程方式突出显示特定行或滚动到特定行?
【问题讨论】:
【参考方案1】:与往常一样,这是详尽记录的。 UIPickerView
的 Apple 文档应该告诉您,您可能想要的方法是 – selectRow:inComponent:animated:
。
【讨论】:
对我来说调用- selectRow:inComponent:animated:
方法是不够的,我还必须以编程方式调用委托-pickerView:didSelectRow:inComponent:
。
对;以编程方式设置所选行不会调用委托方法。如果您想对所有选择更改采取行动,您必须自己调用它。【参考方案2】:
如果你想触发delegate的方法pickerView:didSelectRow:inComponent,你应该手动调用它:
Obj-C
[self.myPickerView selectRow:0 inComponent:0 animated:NO];
[self pickerView:self.myPickerView didSelectRow:4 inComponent:0];
斯威夫特
self.myPickerView.selectRow(0, inComponent: 0, animated: false)
self.pickerView(self.myPickerView, didSelectRow: 0, inComponent: 0)
【讨论】:
只需要在调用委托之后手动添加调度异步,否则非常适合 Swift 4.1【参考方案3】:是的,很简单[picker selectRow:row inComponent:component animated:NO];
【讨论】:
【参考方案4】:在 ios 9 和 XCode 7.3 中工作,在名为 fieldPicker 的选取器视图中对数据进行运行时更改:
// first load your new data to your picker view's data source (not shown here...) then load the data into the picker view using it's delegate
[self.fieldPicker reloadAllComponents];
// now that the data is loaded, select a row in the picker view through it's delegate
[self.fieldPicker selectRow:([self.theFields count] - 1) inComponent:0 animated:NO];
// retrieve the row selected in the picker view to use in setting data from your data source in textboxes etc.
long row = (long)[self.fieldPicker selectedRowInComponent: 0];
【讨论】:
【参考方案5】:
检查您是否调用了方法self.myPickerView.selectRow(0, inComponent: 0, animated: false)
在您将pickerView 添加为子视图。
首先,我调用了方法之前我将pickerView添加为子视图,但它不起作用。因此,我后来调用了它,然后它起作用了!
可能很明显,不是我最聪明的举动,但也许有一天有人会遇到同样的问题,我希望我能提供帮助! :)
【讨论】:
以上是关于我可以以编程方式滚动到 UIPickerView 中所需的行吗?的主要内容,如果未能解决你的问题,请参考以下文章
在 iOS 7/Objective-C 中,如何以编程方式将 UIPickerView 捕捉到它所在的父视图的底部?