在Swift中为控制器属性赋值

时间:2014-06-14 19:20:08

标签: ios objective-c uiviewcontroller swift ios8

我试图在Swift中的视图之间传递一个int变量,但我不确定如何访问其他View控制器的属性。

在Objective C中我会做这样的事情

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
AnsViewController *ansViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ansView"];
ansViewController.num = theNum;
[self presentViewController:ansViewController animated:YES completion:nil];

在另一个viewcontroller.h文件中,我会写这个来声明属性来获取数据

@property (nonatomic) int num;

现在对于Swift我有这个

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let ansViewController : UIViewController = storyBoard.instantiateViewControllerWithIdentifier("ansView") as UIViewController
ansViewController.num = theNum;
self.presentViewController(ansViewController, animated:true, completion:nil)

在另一个视图控制器的.swift文件中,我通过执行

声明了num
let num: int

我很确定这不是正确的方法,因为我在这一行上收到错误

ansViewController.num = theNum;

它说,“UIViewController没有名为num的成员”我将如何解决此错误以及我做错了什么?

由于

1 个答案:

答案 0 :(得分:5)

问题

在Objective C中,您已将ansViewController明确定义为AnsViewController *,其属性为num。

但是,在你的Swift代码中,你已经明确地将ansViewController定义为UIViewController,而不是AnsViewController。所以,编译器不知道这实际上是一个AnsViewController,还是其他一些UIViewController子类,或者只是一个vanilla UIViewController。

现在解决方案。

我们将尝试将返回的值作为AnsViewController进行向下转换,然后在向下转换成功的情况下访问该属性(我假设它始终存在,但是从其他人的上下文中删除)代码和笔尖,我无法确定。

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

// To be safe, let's attempt to downcast the returned value as an AnsViewController
if let ansViewController = storyBoard.instantiateViewControllerWithIdentifier("ansView") as? AnsViewController {
    // We get here if the "as?" succeeds with a non-nil value
    ansViewController.num = theNum;
    self.presentViewController(ansViewController, animated:true, completion:nil)
} else {
    // Out of context, I can't see why this case would (or could) ever happen
}

现在,如果你知道这将永远成功(从我所看到的,-instantiateWith的返回值是确定性的),那么你可以更简洁一点:

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

// Force the downcast as an AnsViewController (this could crash at runtime
// if the return value is nil or not an AnsViewController, so again,
// the previous example is safer
let ansViewController = storyBoard.instantiateViewControllerWithIdentifier("ansView") as AnsViewController
ansViewController.num = theNum;
self.presentViewController(ansViewController, animated:true, completion:nil)