NewOweTableViewController

NewOweTableViewController

我是Xcode和Swift的初学者,我当前正在创建一个应用程序,用户在该应用程序上添加一个人,然后确定他们欠该人的金额或该人欠他/她的金额。

注意:我已经使用核心数据来存储所有值

我实际上想在打开和关闭开关时更改变量的值。例如,在下面,我希望“数量”在开关打开时为负,而在开关关闭时为正。另外,当我尝试执行此操作并将数量变量发送到以前的视图控制器时,由于UISwitch始终显示正值,因此我无法根据该值发送该值。我正在尝试寻找过去3天的解决方案,因此您能帮我吗?在此先多谢

该ViewController

import UIKit

class NewOweTableViewController: UIViewController {

    @IBOutlet weak var titleTextField: UITextField!
    @IBOutlet weak var locationTextField: UITextField!
    @IBOutlet weak var amountTextField: UITextField!
    @IBOutlet weak var datePicker: UIDatePicker!

    let context = (UIApplication.shared.delegate as!
        AppDelegate).persistentContainer.viewContext

    var owe: Owe?
    var dataInfo: [Owe] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.viewWithTag(1)?.isHidden = true
        let saveBTN = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.save, target:self,
                                      action: #selector(saveButtonTapped(_:)))
        let deleteBTN = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.trash, target:self,
                                        action: #selector(deleteButtonTapped(_:)))

        self.navigationItem.rightBarButtonItems = [saveBTN, deleteBTN]

        if !dataInfo.isEmpty {
            titleTextField.text = dataInfo[0].name
            amountTextField.text = (NSString(format: "%.2f", (dataInfo[0].amount) as CVarArg) as String)
            locationTextField.text = dataInfo[0].location
            datePicker.date = dataInfo[0].date!
        }
    }

    @objc func saveButtonTapped(_ sender: UIButton){
        if !dataInfo.isEmpty{
            let data = dataInfo[0]
            data.name = titleTextField.text
            data.amount = Double(amountTextField.text!)!
            data.location = locationTextField.text
            data.date = datePicker.date
        }
        else if titleTextField.text == "" || amountTextField.text == "" || locationTextField.text == "" {
            return
        }
        else{
            let data = Owe(context: context)
            data.name = titleTextField.text
            data.amount = Double(amountTextField.text!)!
            data.location = locationTextField.text
            data.date = datePicker.date
        }

        do {
            try context.save()
            navigationController?.popViewController(animated: true)
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }

    @objc func deleteButtonTapped(_ sender: UIButton){
        if !dataInfo.isEmpty{
            let data = dataInfo[0]
            context.delete(data)

            do {
                try context.save()
                navigationController?.popViewController(animated: true)
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }


    @IBAction func oweSwitch(_ sender: UISwitch) {
        if sender.isOn {
            owe?.amount = (owe?.amount)! * (-1)
            amountTextField.textColor = UIColor.green
        } else {
            owe?.amount = (owe?.amount)! * (1)
            amountTextField.textColor = UIColor.red
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

上一个视图控制器
import UIKit

class PersonDetailTableViewController: UITableViewController {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext


    var totalLabel: UILabel?
    var person: People?
    var owe: Owe?

    @IBOutlet var personTable: UITableView!

    var dataInfo: [Owe] = []
    var selectedObject: [Owe] = []
    var balanceAmount = "Balance: "

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (dataInfo.count)
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = personTable
            .dequeueReusableCell(withIdentifier: "detailsCell", for: indexPath)
        cell.textLabel?.text = dataInfo[indexPath.row].name
        cell.detailTextLabel?.text = "₹ \(dataInfo[indexPath.row].amount)"
        if dataInfo[indexPath.row].amount < 0 {
            cell.detailTextLabel?.textColor = UIColor.red
        } else {
            cell.detailTextLabel?.textColor = UIColor.green
        }
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedObject = [dataInfo[indexPath.row]]
        performSegue(withIdentifier: "addOweDetails", sender: nil)
        tableView.deselectRow(at: indexPath, animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        getData()
        personTable.dataSource = self
        addTotalToNav()
        print(dataInfo as Any)
    }



    // MARK: - Table view data source

    func addTotalToNav() -> Void {
        if let navigationBar = self.navigationController?.navigationBar {
            let totalFrame = CGRect(x: 10, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height)

            totalLabel = UILabel(frame: totalFrame)
            totalLabel?.text = balanceAmount
            totalLabel?.tag = 1
            totalLabel?.font = UIFont.boldSystemFont(ofSize: 14)
            totalLabel?.textColor = UIColor.red
//            navigationBar.large = totalLabel?.text
            self.title = totalLabel?.text

        }
    }


    func getData() -> Void {
        do{
            dataInfo = try context.fetch(Owe.fetchRequest())
            var total:Double = 0.00
            for i in 0 ..< dataInfo.count {
                total += dataInfo[i].amount as! Double
            }
            balanceAmount = "Balance: ₹" + (NSString(format: "%.2f", total as CVarArg) as String)
        }
        catch{
            print("Fetching Failed")
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! NewOweTableViewController
        vc.dataInfo = selectedObject
        selectedObject.removeAll()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getData()
        personTable.reloadData()
        if (self.navigationController?.navigationBar.viewWithTag(1)?.isHidden == true){
            self.navigationController?.navigationBar.viewWithTag(1)?.removeFromSuperview()
            addTotalToNav()
        }
    }

}

欠款的核心数据
import UIKit
import CoreData

@objc(Owe)
public class Owe: NSManagedObject {
    var date: Date? {

        get{
            return rawDate as Date?
        }
        set {
            rawDate = newValue as NSDate?
        }
    }

    convenience init?(name: String?, location: String?, amount: Double, date: Date?) {
        let appDelegate = UIApplication.shared.delegate as? AppDelegate

        guard let context = appDelegate?.persistentContainer.viewContext
            else {
                return nil
            }

        self.init(entity: Owe.entity(), insertInto: context)

        self.name = name
        self.location = location
        self.amount = amount
        self.date = date

        }
    }

最佳答案

您好,欢迎来到Swift社区!

如果我理解正确,则您正在尝试将更新从NewOweTableViewController向后传播到PersonDetailTableViewController。在这种情况下,使用MVC架构实现此目的的简便方法是在NewOweTableViewController中初始化闭包时将其传递给PersonDetailTableViewController

为此,

  • 更新NewOweTableViewController并添加一个闭包属性。
    class NewOweTableViewController: UIViewController {
    
        // ...
    
        var switchValueUpdate: ((Bool) -> ())?
    
        // ...
    }
    
  • 确保您在@IBAction中调用链接到NewOweTableViewController中的开关的闭包
    @IBAction func oweSwitch(_ sender: UISwitch) {
        if sender.isOn {
            owe?.amount = (owe?.amount)! * (-1)
            amountTextField.textColor = UIColor.green
        } else {
            owe?.amount = (owe?.amount)! * (1)
            amountTextField.textColor = UIColor.red
        }
        switchValueUpdate?(sender.isOn)
    }
    
  • 更新PersonDetailTableViewController设置关闭
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
        let vc = segue.destination as! NewOweTableViewController
        vc.dataInfo = selectedObject
        selectedObject.removeAll()
    
        vc.switchValueUpdate = { (isOn) in
            // Here you go, update PersonDetailTableViewController to reflect changes related to the switch!
        }
    }
    

  • 而已!如果您对此代码有任何疑问,请告诉我,希望它能对您有所帮助!

    关于ios - 如何通过UISwitch更改变量的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49498594/

    10-12 21:05