在Swift中给控制器属性赋值

4

我将尝试在Swift中在视图之间传递一个整数变量,但我不确定如何访问另一个视图控制器的属性。

在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的成员”。我该如何解决这个错误,我做错了什么?

谢谢


这个 let num: int 的代码在哪里?你能添加更多的代码吗? - lucianomarisi
我将 let num : int 这行代码放在 AnsViewController 的 Swift 文件中,放在所有 @IBOutlet var 行的下面。 - lagoon
1个回答

5
问题:
在Objective C中,您明确将ansViewController定义为AnsViewController*,它具有属性num。
但是,在您的Swift代码中,您明确将ansViewController定义为UIViewController,而不是AnsViewController。因此,编译器不知道这是否实际上是AnsViewController、其他UIViewController子类或仅仅是普通的UIViewController。
解决方案:
我们将尝试将返回值强制转换为AnsViewController,然后在强制转换成功后访问该属性(我假设它总是成功的,但是从您的代码和nibs的其他部分中无法确定)。
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)

谢谢!这似乎清除了所有错误,但又产生了一个新的错误。在 ansViewController.num = theNum 的那一行,出现了一个错误,说 CInt 无法转换为 Int。我还不得不更改声明 num 的部分,将 var num: Int = 0 来消除错误。我应该这样做吗? - lagoon
我认为我出现了这个错误是因为我不得不使用bridgeToObjectiveC().intValue从文本字段中获取int值。 - lagoon
我不确定theNum是从哪里来的,但是可以试试这个:ansViewController.num = Int(theNum) - Ryan
这个方法能够起作用的原因是Swift在类型方面非常严格,不将Ints和CInts视为可互换的。您需要从CInt对象初始化一个新的Int对象。Int(cInt: CInt)本质上就是被调用的init方法,它可以从CInt创建一个Int。 - Ryan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接