gpt4 book ai didi

ios - pickerView 和操作按钮

转载 作者:行者123 更新时间:2023-11-30 12:59:39 24 4
gpt4 key购买 nike

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

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

这是我尝试过的:

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

如何为选取器 View 指定已选定的行,以便我可以在按钮功能中使用它?

最佳答案

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com