简体   繁体   中英

Passing Data through View Controllers with Swift without Using Storyboard

I am trying to create a transition between two View Controllers (the second presented modally) that passes data parsed from an API. A button is created based on this data (it affects what the button says). This is within the closure of an API call, and I store the returned data into a variable within the class (ie self.data = returnedData)

let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(0, 100, UIScreen.mainScreen().bounds.width, 50)
button.backgroundColor = UIColor.whiteColor()
button.setTitle("\(buttonTitleInfo)", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

self.view.addSubview(button)

Then:

func buttonAction(sender:UIButton!)
{
    // the data is usable here but I don't know how to pass it via this button 
    let viewController:UberWebviewController = UberWebviewController()
    self.navigationController?.presentViewController(viewController, animated: true, completion: nil)
}

I am not using Storyboard or IB and most of the tutorials/solutions I have found use things specific to those.

How can I pass the returned data without using those?

Make a var on UberWebviewController of the type you want, for example [Any]? :

var dataFromAPI : [Any]?

Then set it after creating the controller but before presenting it:

let viewController = UberWebviewController()
viewController.dataFromAPI = whateverYourDataIs
self.navigationController?.presentViewController(viewController, animated: true, completion: nil)

Then within UberWebviewController , unwrap the optional:

func doSomething {
    if let myData = dataFromAPI {
        // do something with myData
    } else {
        // no data was obtained
    }
}

Alternatively, you could make dataFromAPI non-optional and pass the data in the initializer:

class UberWebviewController : UIViewController {

    var dataFromAPI : [Any]

    init(data someData : [Any]) {
        self.dataFromAPI = someData
        super.init()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

Then just pass it during initialization:

let viewController = UberWebviewController(data: whateverYourDataIs)
self.navigationController?.presentViewController(viewController, animated: true, completion: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM