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

例如,我在pickerView中有多个项目,而在核心数据中又有计数器属性,因此我需要做的就是一旦我从pickerView中选择了一个特定项目并单击按钮,计数器属性应增加一个。

这是我尝试过的:

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)
    }
}


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

最佳答案

如果您创建另一个名为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)
    }
}

关于ios - pickerView和操作按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39996631/

10-15 12:39