我尝试使用
@IBOutlet weak var textField: UITextField!
@IBAction func saveTextToVar(sender: UIButton) {
var exercises: NSString = textField.text
}
...
override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) {
if (segue.identifier == "segueTest") {
var svc = segue!.destinationViewController as ViewController;
svc.exercises = textField.text
}
将 textField 中键入的变量“exercise”保存到 ViewController ,其中我声明了变量
class ViewController: UIViewController,UIPickerViewDelegate {
var exercises = ["a","b","c"]
(它应该用作 UIpickerView 中的组件)但是在ViewController2上发生了一个错误说法。 'String'不能转换为'[String]'
答案 0 :(得分:0)
当然可以!您可以在某处保存PickerView的标题(CoreData可以永久保存它们,如果您不需要永久存储它们,可以保存普通数组),然后在UIPickerViewDelegate中动态加载它们
pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
在我自己的应用程序中,我有一个dataModel
,我在其中存储了应用程序中给定模块的所有相关数据。我像这样动态加载PickerView的标题:
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return dataModel.levels[row]
}
我也实施了
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataModel.levels.count
}
确保它在组件中始终具有正确的行数。
答案 1 :(得分:0)
正如错误所示,您的练习var被输入为字符串数组,并且您正在将字符串值传递给它。为了完成这项工作,您必须将文本字段中的字符串附加到prepareForSegue方法中的练习数组
override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) {
if (segue.identifier == "segueTest") {
var svc = segue!.destinationViewController as ViewController;
svc.exercises.append(textField.text)
}
EDITED:由于您需要从根视图控制器添加多个练习,您应该将它们全部保存在根视图控制器中的变量中,然后将所有新值添加到ViewController练习中。所以你的代码看起来应该像下面的
@IBOutlet weak var textField: UITextField!
var exercises: [String] = []
@IBAction func saveTextToVar(sender: UIButton) {
exercises.append(textField.text)
}
override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) {
if (segue.identifier == "segueTest") {
var svc = segue!.destinationViewController as ViewController;
svc.exercises = svc.exercises + self.exercises
}}