pickerView和action按钮

时间:2016-10-12 10:44:39

标签: ios swift action

当我尝试从我的pickerView对特定行执行操作时,我遇到了一个问题。

例如,我在pickerView中有多个项目,并且在核心数据中我有计数器属性,所以我需要做的是一旦我从pickerView中选择一个特定项目并点击按钮,计数器属性应该增加一个。 / p>

以下是我的尝试:

var MEDARRAY = [NSManagedObject]()
var Counter:NSInteger?
var thecounte:Int?

@IBOutlet weak var thepicker: UIPickerView!


func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return MEDARRAY.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    self.view.endEditing(true)
    return String(describing: MEDARRAY[row].value(forKey: "medName")!)
}
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
    let NumDay = self.MEDARRAY[row].value(forKey: "medNumDay") as? NSInteger
    let NumMed = self.MEDARRAY[row].value(forKey: "medNum") as? NSInteger
    Counter = (self.MEDARRAY[row].value(forKey: "takenCounter") as? NSInteger)!
    TotalDose.text = String(NumDay! * NumMed!)
    RemainDose.text = String(Int(TotalDose.text!)! - Counter!)

}
//here is the button should increase the counter 
    @IBAction func Taken(_ sender: AnyObject) {
    let Appdelegate = UIApplication.shared.delegate as? AppDelegate
    let context = Appdelegate?.persistentContainer.viewContext
    let newCounter = Counter! + 1
    do{
        // how to specified the did selected row in here to update the counter value for that row
        self.MEDARRAY[newCounter].setValue(newCounter, forKey: "takenCounter")
        try context?.save()
    }catch{
        print(error)
    }
}

如何为选择器视图指定选定的行,以便在按钮功能中使用它?

1 个答案:

答案 0 :(得分:0)

如果你创建另一个名为selectedObject的变量,那么:

var selectedObject = NSManagedObject()

并使用pickerViewDidSelectRow方法更新它:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
    let NumDay = self.MEDARRAY[row].value(forKey: "medNumDay") as? NSInteger
    let NumMed = self.MEDARRAY[row].value(forKey: "medNum") as? NSInteger
    Counter = (self.MEDARRAY[row].value(forKey: "takenCounter") as? NSInteger)!

    //updates whenever a new row is selected
    selectedObject = self.MEDARRAY[row]

    TotalDose.text = String(NumDay! * NumMed!)
    RemainDose.text = String(Int(TotalDose.text!)! - Counter!)
}

然后你可以在按下按钮时调用它,它会给你最近选择的行,这样你就可以增加它的数量""字段。

@IBAction func Taken(_ sender: AnyObject) {
    let Appdelegate = UIApplication.shared.delegate as? AppDelegate
    let context = Appdelegate?.persistentContainer.viewContext
    let newCounter = Counter! + 1
    do{
        //initialize index variable
        let index = MEDARRAY.indexOf(selectedObject)

        //use index in your MEDARRAY call
        self.MEDARRAY[index].setValue(newCounter, forKey: "takenCounter")
        try context?.save()
    }catch{
        print(error)
    }
}