我对 Swift 和 Xcode 几乎是全新的,所以请原谅我在这个领域缺乏知识。 目前我有一个带有标签的 View Controller 。我想在此之前添加一个 View ,其中包含一个用户在其中输入名称的文本字段,然后应用程序转到带有标签的第二个 View ,其中用户输入的名称放在标签上。
我知道这是非常基本的,但我找不到任何好的解决方案,因为我不太确定要搜索什么。如果有人有一段代码或一个好的来源的链接,我很乐意看到它。
谢谢!
编辑:我对此知之甚少。使用两个 View 时是否需要导航 Controller ?我需要两个 ViewController.swift 文件吗?
最佳答案
只需 12 个简单步骤即可完成此操作:
1) 是的。我建议使用 Navigation Controller
。使用单一 View 应用程序开始一个新项目。
2) 在 Storyboard 中选择 ViewController
,然后从上面的菜单栏中选择 Editor->Embed In->Navigation Controller
。
3) 拖出一个 UIButton
和一个 UITextField
并将它们放在您的第一个 ViewController
中。
4) 您需要将 IBOutlet
添加到您的文本字段,以便您可以从中读取文本。通过单击 Xcode 右上角的 Tuxedo 图标,显示助理编辑器。单击 Storyboard 中的 ViewController
。右侧的编辑器 Pane 将显示 ViewController
的代码。按住 Control 键并从文本字段拖动到右 Pane 中的代码。当您位于 class ViewController : UIViewController {
正下方的空间时,松开鼠标按钮。在弹出窗口中,将Connection 设置为Outlet,将名称设置为textField
,然后按Connect。这会将行 @IBOutlet weak var textField: UITextField!
添加到您的 ViewController
。
5) 现在是时候添加第二个 View Controller 了。从菜单中选择 File->New->File...
。在对话框中,确保在左侧选择 iOS 下的 Source,然后选择 Cocoa Touch Class 并按 Next。将类命名为 SecondViewController
并使其成为 UIViewController
的子类。按下一步,然后按创建。
6) 在 Storyboard 中,拖出一个 UIViewController
并将其放在第一个 ViewController
的右侧。选择新的 ViewController
并通过单击 Tuxedo 图标下方的图标行中从左数第 3 个图标打开 Identity Inspector。 (提示:如果您将鼠标悬停在图标上,它会告诉您它们的作用)。将类更改为 SecondViewController
。
7) 在 Storyboard 中,从第一个 ViewController
中的按钮按住 control 并拖动(按住 control 并拖动)到新的 SecondViewController
。在弹出窗口中选择 Show 作为 Action Segue。
8) 拖出一个Label,放入SecondViewController
。像在第 4 步中那样向它添加一个 IBOutlet
并将其命名为 mylabel。
9) 在 SecondViewController
的代码中添加一个新的实例变量,如下所示:var firstVCtext = ""
10) 在第一个ViewController
中添加这个方法:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
let secondVC = segue.destinationViewController as SecondViewController
secondVC.firstVCtext = textField.text
}
11) 在SecondViewController
中,将这行代码添加到viewDidLoad
方法中:mylabel.text = firstVCtext
12) 运行程序!
关于ios - 在 Swift (Xcode 6) 的其他 View 中使用来自 View 的输入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25345262/