我正在尝试设置一个选择器,它会根据某些条件显示不同的结果。唯一的问题是我需要将 dataSource
(将显示的选择器数据)放在 viewDidLoad
之外。如果满足条件,我需要 viewDidLoad 来加载适当的数据。但是,对于我见过的处理选择器的代码,似乎 dataSource 数组放置在 viewDidLoad 之外(我认为委托(delegate)方法可以使用该值)。我只是想知道是否可以将此 dataSource
放入 viewDidLoad
中,以便它能够识别它,或者是否有办法在 之外运行 Switch 或 If 语句>viewDidLoad
并在类中。
import UIKit
import Parse
class VC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
var pickerData = [String]()
@IBOutlet weak var namePicker: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
namePicker.dataSource = self
namePicker.delegate = self
//here I want the picker to show something different depending on the value of nameOfPerson. I changed the order of the array because the picker selects the first name of the array as the default.
switch nameOfPerson
{
case "Carly":
let pickerData = ["Carly","Jeff","Bob","Anita"]
case "Jeff":
let pickerData = ["Jeff","Carly","Bob","Anita"]
case "Bob":
let pickerData = ["Bob","Carly","Jeff","Anita"]
case "Anita":
let pickerData = ["Anita","Carly","Jeff","Bob"]
}
}
func numberOfComponents(in 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]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
}
}
最佳答案
I am just wondering if I can place this dataSource into viewDidLoad so that it would recognize it, or if there was a way to run a Switch or If statement outside the viewDidLoad and in the class
没有。数据源方法必须是方法,即位于类顶层的函数,以便 Objective-C 能够看到它们。因此,数据本身必须对数据源方法可见,并且在 viewDidLoad 和数据源方法之间共享数据的唯一连贯方式是作为属性,例如 var pickerData >.
你的代码有什么问题是let
:
case "Carly":
let pickerData = ["Carly","Jeff","Bob","Anita"]
case "Jeff":
let pickerData = ["Jeff","Carly","Bob","Anita"]
case "Bob":
let pickerData = ["Bob","Carly","Jeff","Anita"]
case "Anita":
let pickerData = ["Anita","Carly","Jeff","Bob"]
}
从每个案例中删除术语let
!否则,您只是设置一个临时局部变量 pickerData
,这不是您想要做的。您想要设置您声明的属性,如下所示:
var pickerData = [String]()
...而你的代码没有这样做!你想要的是这样的:
case "Carly":
self.pickerData = ["Carly","Jeff","Bob","Anita"]
case "Jeff":
self.pickerData = ["Jeff","Carly","Bob","Anita"]
case "Bob":
self.pickerData = ["Bob","Carly","Jeff","Anita"]
case "Anita":
self.pickerData = ["Anita","Carly","Jeff","Bob"]
}
(当然,您还需要一个 default
案例。)
最后,为了安全起见,重新加载数据:
self.namePicker.reloadAllComponents()
关于swift - Xcode Swift 3 选择器 : Putting the DataSource in ViewDidLoad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42502026/