【问题标题】:how do i append an object to an array from a pickerView如何从pickerView将对象附加到数组
【发布时间】:2019-10-16 10:44:35
【问题描述】:

我在 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])
    }
}

【问题讨论】:

    标签: arrays swift append uipickerview


    【解决方案1】:

    nvm ... 明白了。

    在顶层声明 var。

    var test = Formula()
    

    didSelectRow

    test = allFormula.arr[row]
    

    IBAction

    AllFormula.newArr.append(test)
    

    【讨论】:

      猜你喜欢
      • 2023-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多