如何通过UISwitch更改变量的值?

时间:2018-03-26 18:49:45

标签: ios swift xcode core-data uiswitch

我是Xcode和Swift的初学者,我目前正在创建一个应用程序,用户在应用程序中添加一个人,然后就是他们欠那个人或那个人欠他/她的钱。

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

我实际上想要在打开和关闭开关时更改变量的值。例如,在下面我希望开关打开时“金额”为负数,关闭时金额为正数。此外,当我尝试这样做并将金额变量发送到前一个视图控制器时,我无法根据UISwitch发送值,因为它总是显示正数。我试图从过去3天找到解决方案,所以能帮助我吗?非常感谢提前

Owe 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

        }
    }

1 个答案:

答案 0 :(得分:1)

您好,欢迎来到Swift社区!

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

为了做到这一点,

  1. 更新NewOweTableViewController并添加一个闭包属性。

    class NewOweTableViewController: UIViewController {
    
        // ...
    
        var switchValueUpdate: ((Bool) -> ())?
    
        // ...
    }
    
  2. 请务必在@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)
    }
    
  3. 更新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!
        }
    }
    
  4. 就是这样!如果您对该代码有任何疑问,请告诉我,希望它有所帮助!