UIPickerView pickerView(_:titleForRow:forComponent:) 方法
UIPickerView pickerView(_:titleForRow:forComponent:) method
我使用 UIPickerView
及其方法 pickerView(_:titleForRow:forComponent:)
来填充行。一切正常,我可以通过 UI 查看行。我想知道方法被调用了多少次——例如,我有一个组件和 3 行,如果我通过打印命令跟踪方法调用,我发现有 8 次调用(运行)。
我想对每一行执行特定操作,但只是一次。任何提示我做错了什么以及我应该如何做得更好?
谢谢
pickerView(_:titleForRow:forComponent:)
由Picker View需要在给定组件中用于给定行的标题时调用。因此,只要需要标题,就会调用委托函数。你可能已经注意到这些方法可以被调用多次,这是正常的。
在你的:
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
你有row
,你可以创建一个字典来检查你之前是否设置过一个值。像这样:
var dictionary = [Int: Bool]()
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if let value = dictionary[row] {
if !value {
// set value, the value of row has not been set before
...
// set that rows value to true so that you know it has been set
dictionary[row] = true
}
}
return "some string"
}
您可以在您的数据中添加一个布尔标志,用于确定是否进行调用。
我使用 UIPickerView
及其方法 pickerView(_:titleForRow:forComponent:)
来填充行。一切正常,我可以通过 UI 查看行。我想知道方法被调用了多少次——例如,我有一个组件和 3 行,如果我通过打印命令跟踪方法调用,我发现有 8 次调用(运行)。
我想对每一行执行特定操作,但只是一次。任何提示我做错了什么以及我应该如何做得更好? 谢谢
pickerView(_:titleForRow:forComponent:)
由Picker View需要在给定组件中用于给定行的标题时调用。因此,只要需要标题,就会调用委托函数。你可能已经注意到这些方法可以被调用多次,这是正常的。
在你的:
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
你有row
,你可以创建一个字典来检查你之前是否设置过一个值。像这样:
var dictionary = [Int: Bool]()
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if let value = dictionary[row] {
if !value {
// set value, the value of row has not been set before
...
// set that rows value to true so that you know it has been set
dictionary[row] = true
}
}
return "some string"
}
您可以在您的数据中添加一个布尔标志,用于确定是否进行调用。