我如何从pickerView将对象附加到数组

时间:2019-05-30 18:47:09

标签: arrays swift append uipickerview

我有一个在pickerView中使用的类对象数组。我需要将该对象附加到通过UIButton支持tableView的另一个数组。我无法弄清楚如何获取pickerViews索引,我得到的最接近的错误是“无法将类型'Int'的值转换为预期的参数类型'Formula'”,不确定我做错了什么,并在搜索了几天后才问这里。预先谢谢你。

class Formula {
   var formulaNumber: String = ""
   var formulaTitle: String = ""
   var base: String = ""
   var baseValue: Double = 0.0
}



class AllFormula {

   var arr: [Formula] = []
   static var newArr : [Formula] = []


init() {

    let test1 = Formula()
    test1.formulaNumber = "test1"
    test1.formulaTitle = "test1"
    test1.base = "test1"
    test1.baseValue = 10

    let test2 = Formula()
    test2.formulaNumber = "test2"
    test2.formulaTitle = "test2"
    test2.base = "test2"
    test2.baseValue = 20

    arr = [test1, test2]
    AllFormula.newArr = []
    }

}


class AddViewControllerTest : UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {


    let allFormula = AllFormula()
    let numberOfBatches = (1...100).map { String($0) }
    @IBOutlet weak var picker: UIPickerView!

    override func viewDidLoad() {
    super.viewDidLoad()
        picker.dataSource = self
        picker.delegate = self

}



func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 2
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if component == 0 {
        return allFormula.arr.count
    }else{
        return numberOfBatches.count
    }

}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if component == 0 {
        return allFormula.arr[row].formulaNumber

    }
    return numberOfBatches[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    let chosenRun = allFormula.arr[row]
    let Batches = self.numberOfBatches[row]

    //these print the correct formulas and number of batches
    print(chosenRun)
    print(Batches)

}


@IBAction func AddRunTapped(_ sender: Any) {
    //trying to get the object to pass into new array.
    AllFormula.newArr.append(picker.selectedRow(inComponent: 0))

    //also tried this, which works if it were inside the didSelectRow for the picker view. but i need it on a IBAction.
    AllFormula.newArr.append(allFormulas.arr[row])

    // where as if i choose the exact index it works.
    AllFormula.newArr.append(allFormulas.arr[1])
    }
}

1 个答案:

答案 0 :(得分:0)

nvm ...明白了。

在顶层声明变量。

var test = Formula()

didSelectRow

test = allFormula.arr[row]

IBAction

AllFormula.newArr.append(test)