簡體   English   中英

在 Swift (Xcode 6) 的其他視圖中使用視圖中輸入的文本

[英]Use entered text from view in other view in Swift (Xcode 6)

我對 Swift 和 Xcode 幾乎完全陌生,所以請原諒我缺乏這方面的知識。 目前我有一個帶有標簽的視圖控制器。 我想在此之前添加一個視圖,帶有用戶輸入名稱的文本字段,然后應用程序轉到帶有標簽的第二個視圖,其中用戶輸入的名稱放置在標簽上。

我知道這是非常基本的,但我找不到任何好的解決方案,因為我不太確定要搜索什么。 如果有人有一段代碼或一個好的來源的鏈接,我很樂意看到它。

謝謝!

編輯:我真的對此知之甚少。 使用兩個視圖時是否需要導航控制器? 我需要兩個 ViewController.swift 文件嗎?

以下是您通過 12 個簡單步驟完成的方法:

1) 是的。 我建議使用Navigation Controller 使用Single View Application開始一個新項目。

2) 在 Storyboard 中選擇ViewController並從上方的菜單欄中選擇Editor->Embed In->Navigation Controller

3) 拖出一個UIButton和一個UITextField並將它們放在你的第一個ViewController

4) 您需要一個IBOutlet到您的文本字段,以便您可以從中讀取文本。 單擊Xcode右上角的Tuxedo圖標,顯示 Assistant 編輯器 單擊 Storyboard 中的ViewController 右側的編輯器窗格將顯示ViewController的代碼。 按住Control鍵並從文本字段拖動到右側窗格中的代碼。 當您位於class ViewController : UIViewController {下方的空間時,松開鼠標按鈕class ViewController : UIViewController { 在彈出窗口中,將Connection設置為Outlet ,將名稱設置為textField並按Connect 這將添加行@IBOutlet weak var textField: UITextField! 到您的ViewController

5) 現在是添加第二個視圖控制器的時候了。 從菜單中選擇File->New->File... 在對話框中,確保在左側選擇iOS下的Source ,然后選擇Cocoa Touch Class並按Next 將類命名為SecondViewController並使其成為UIViewController的子類。 下一步,然后創建

6) 在 Storyboard 中,拖出一個UIViewController並將其放到第一個ViewController的右側。 選擇新的ViewController並通過單擊Tuxedo圖標下方圖標行中從左側開始的第三個圖標打開Identity Inspector (提示:如果您將鼠標懸停在圖標上,它會告訴您它們的作用)。 將類更改為SecondViewController

7) 在 Storyboard 中,從第一個ViewController的按鈕控制拖動(按住控制並拖動)到新的SecondViewController 在彈出窗口中選擇Show as the 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) 運行程序!

另一個很好的教程,這里有代碼和圖像:

http://www.jamesrambles.com/ios-swift-passing-data-between-viewcontrollers/

要將數據從一個視圖移動到另一個視圖,使用 segue(發音為 seg-way)是最簡單的。 一個例子在這里:

http://makeapppie.com/2014/07/01/swift-swift-using-segues-and-delegates-in-navigation-controllers-part-1-the-template/

如果您使用 Google 搜索 Swift 和 Segue,您可能會找到更多示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM