使用Swift通过View控制器传递数据而不使用Storyboard

时间:2014-11-20 19:29:47

标签: ios swift

我正在尝试在两个View Controller之间创建一个转换(第二个呈现模态),它传递从API解析的数据。根据此数据创建一个按钮(它会影响按钮的内容)。这是在API调用的闭包内,我将返回的数据存储到类中的变量(即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)

然后:

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

我没有使用Storyboard或IB,而且我发现的大多数教程/解决方案都使用了特定的东西。

如何在不使用这些数据的情况下传递返回的数据?

1 个答案:

答案 0 :(得分:14)

制作所需类型UberWebviewController的变量,例如[Any]?

var dataFromAPI : [Any]?

然后在创建控制器之后但在呈现之前设置它:

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

然后在UberWebviewController内打开可选的:

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

或者,您可以使dataFromAPI非可选,并在初始值设定项中传递数据:

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

}

然后在初始化期间传递它:

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