swift - adding values between 2 view controllers by prepareforsegue

十年热恋 提交于 2019-12-25 02:54:01

问题


I have 2 ViewControllers: ViewController1, ViewController2. An "Add" button in ViewController1 will bring up ViewController2. User will then enter in values into ViewController2 which will then be passed back into ViewController1 by prepareforsegue. These values are then append onto the properties of type array in viewcontroller1.

This is being repeated, whereby the user continue pressing the add button to bring up ViewController2 from ViewController1, and then add in new values to be appended onto the properties of array type in ViewController1 via prepareforsegue.

However this is not the case after the first set of values being appended from ViewController2. The second set of values will overwrite the first set of values.

Example.

After the first passed -> force =[1], stiffness[1]

After the second passed -> force=[2], stiffness[2]

I will want this -> force = [1,2], stiffness[1,2]

I want to continue adding until -> force = [1,2,3,4,5], stiffness[1,2,3,4,5]

ViewController1

class ViewController1: UITableViewController, UITableViewDataSource {
    var force = [Float]()
    var stiffness = [Float] ()
@IBAction func Add(sender: AnyObject) { }

}

ViewController2

class ViewController2: UIViewController {
        var forceVar : Float = 0.0
        var stiffVar : Float = 0.0

@IBAction func submit(sender: AnyObject) {
        self.performSegueWithIdentifier("springSubmit", sender: sender)
        }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if(segue.identifier == "springSubmit") {
            var svcSubmitVariables = segue.destinationViewController as ViewController1

            svcSubmitVariables.force.append(forceVar)
            svcSubmitVariables.stiffness.append(stiffVar)   
        }

回答1:


The performSegueWithIdentifier method will always initialize new view controller so in your example view controller that showed ViewController2 is different object from object initialized after submitting data and ofc this newly initialized object will have only initialize values. To achieve what you are looking for you will need to declare a function on your ViewController1 that will append data to your arrays, pass that function to ViewController2 and call it on submit method so your view controllers would look similar like these:

ViewController1

class ViewController1: UITableViewController, UITableViewDataSource {

    var force = [Float]()
    var stiffness = [Float] ()

    override func viewWillAppear(animated: Bool) {

     //check if values are updated
     println(force)
     println(stiffness)
    }

    @IBAction func Add(sender: AnyObject) { 
        self.performSegueWithIdentifier("viewController2", sender: sender)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if(segue.identifier == "viewController2") {

            var addVariables = segue.destinationViewController as ViewController2
            addVariables.submitFunc = appendData
        }          
    }

    func appendData(newForce:Float,newStiffness:Force){
        force.append(newForce)
        stiffness.append(newStiffness)
    }       
}

ViewController2

class ViewController2: UIViewController {
    var forceVar : Float = 0.0
    var stiffVar : Float = 0.0
    var submitFunc:((newForce:Float,newStiff:Float)->())!

    @IBAction func submit(sender: AnyObject) {

        submitFunc(forceVar,stiffVar)
        self.dismissViewControllerAnimated(false, completion: nil)

    }
}



回答2:


ViewController

    import UIKit

class ViewController: UITableViewController, UITableViewDataSource {

    var springNumber:NSInteger = 0
    var force = [Float]()
    var stiffness = [Float] ()

    // MARK: UITableViewDataSource
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView,
        numberOfRowsInSection section: Int) -> Int {
            return springNumber
    }

    override func tableView(tableView: UITableView,
        cellForRowAtIndexPath
        indexPath: NSIndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
                as UITableViewCell

            cell.textLabel!.text = "Spring \(indexPath.row)"

            return cell
    }

    func fwall() -> Float {
        for rows in 0..<(springNumber+1)  {
            force[0] = force[0] + force[rows]
        }
        force[0] = -(force[0])
        return force[0]
    }

    override func viewWillAppear(animated: Bool) {

        super.viewWillAppear(animated)

        title = "Springs' Variables"
            tableView.registerClass(UITableViewCell.self,
                forCellReuseIdentifier: "Cell")

        if(springNumber==0) {
            force.append(0.0) }

        println(force)
        println(stiffness)
    }

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

    //Adding Values
    @IBAction func Add(sender: AnyObject) {
        self.performSegueWithIdentifier("addSpring", sender: sender)
    }

    @IBAction func solve_Pressed(sender: AnyObject) {
        self.fwall()
        self.performSegueWithIdentifier("Solve", sender: sender)
    }

    func appendData (newForce: Float, newStiffness:Float, newSpring: NSInteger) {
        force.append(newForce)
        stiffness.append(newStiffness)
        springNumber = newSpring
        println(springNumber)
        println(force)
        println(stiffness)
    }

    override func prepareForSegue ( segue: UIStoryboardSegue, sender: AnyObject!) {

        if (segue.identifier == "addSpring") {
            var addVariables = segue.destinationViewController as SpringTableViewControllerInsertVariables
                addVariables.submitFunc = appendData
        }

        if (segue.identifier == "Solve") {
            var svcViewController2 = segue.destinationViewController as ViewController2
            svcViewController2.forceView2 = self.force
            svcViewController2.stiffView2 = self.stiffness
            svcViewController2.springNumView2 = self.springNumber
        }

        if (segue.identifier == "showDetail") {

        }
    }
}

Code for springTableViewControllerInsertVariables

import UIKit

class SpringTableViewControllerInsertVariables: UIViewController {

var forceVar : Float = 0.0
var stiffVar : Float = 0.0
var springNum : NSInteger = 0

var submitFunc: ((newForce:Float,newStiff:Float,newSpring:NSInteger)->())!

@IBOutlet weak var image: UIImageView!

var imageArray :[UIImage] = [UIImage(named: "springAtWall.jpg")!, UIImage(named:"spring.jpg")!]

override func viewDidLoad() {
    if(springNum == 0) {image.image = imageArray[0] }
    else {image.image = imageArray[1] }
}

@IBOutlet weak var force: UILabel!
@IBOutlet weak var forceEntered: UITextField!

@IBOutlet weak var stiffness: UILabel!
@IBOutlet weak var stiffnessEntered: UITextField!

@IBAction func checkboxed(sender: AnyObject) {
    //when checkedboxed is checked here. 
    //1)UIImage is changed
    //2)calculate2 function is used for calculate1
}

@IBAction func submit(sender: AnyObject) {
    //might not work because springNum will be initialise to zero when this viewcontroller starts...

    forceVar = (forceEntered.text as NSString).floatValue
    stiffVar = (stiffnessEntered.text as NSString).floatValue

    springNum = springNum + 1

    submitFunc(newForce: forceVar ,newStiff: stiffVar, newSpring: springNum)

    self.dismissViewControllerAnimated(false, completion: nil)

}

}



来源:https://stackoverflow.com/questions/28557738/swift-adding-values-between-2-view-controllers-by-prepareforsegue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!