我正在尝试设置一个根据特定条件显示不同结果的选择器。唯一的问题是我需要将dataSource
(将显示的选择器数据)放在viewDidLoad
之外。如果条件满足,我需要viewDidLoad
加载适当的数据。但是,使用代码处理我所见过的拾取器,似乎dataSource
数组放在viewDidLoad
之外(我认为委托方法可以使用该值)。我只是想知道我是否可以将此dataSource
放入viewDidLoad
以便它能够识别它,或者是否有办法在viewDidLoad
之外运行Switch或If语句类。
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)
{
}
}
答案 0 :(得分:2)
我只是想知道我是否可以将此dataSource放入viewDidLoad以便它能识别它,或者是否有办法在viewDidLoad和类中运行Switch或If语句
没有。数据源方法必须是方法,即在类的顶级函数,以便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()
答案 1 :(得分:0)
数据源需要在视图加载时设置,但您可以将其加载到您需要的任何位置。
内部viewDidLoad
picker.datasource = self
任何地方,您都可以设置实际数据;
picker.dataArray = "example, anything"
我不确定我完全理解你。如果你没有找到这个,请告诉我。