Alert Controller 中實現可編輯文本字輸入框教程

做者:Arthur Knopper,原文連接,原文日期:2015-12-21
譯者:pmst;校對:Cee;定稿:千葉知風ios

UIAlertController 類不只用於呈現警告彈窗,還可以提供 Text Fields 來獲取文本信息輸入。本教程演示了從用戶處獲取帳號和密碼,並打印到終端中。此教程開發環境爲 Xcode 7.2 以及 iOS 9。git

打開X code,建立一個 Single View Application。輸入項目名稱:IOS9TextFieldAlertControllerTutorial,接着填寫你獨有的 Organization Name 以及 Organization Identifier。選擇語言爲 Swift 並確保設備爲 iPhone 。github

前往 Storyboard。從 Object Library(譯者注:快捷鍵 Command + Option + Control + 3) 中拖拽一個按鈕(UIButton)到主視圖中。雙擊按鈕設置 title 名爲 「Log in」。此刻保持按鈕爲選中狀態,按下 Ctrl 鍵,使用鼠標左鍵拖拽一條線到主視圖上方,彈出黑色信息框,使用 Shift 鍵選中「Vertical Spacing to Top Layout Guide」和「Center Horizontally in Container」兩個選項。swift

Storyboard 應該是這個樣子的。閉包

(譯者注:也許你的界面呈現了黃色約束警告,你須要使用 Command + Option + = 快捷鍵來更新下。)ide

選中 Assistant Editor ,確保 ViewControllers.swift 可見。選中按鈕使用 Ctrl + 左鍵拖拽方式建立以下 Action。ui

ViewController 類中實現 login 方法:spa

@IBAction func login(sender: AnyObject) {
    // 1.
    var usernameTextField: UITextField?
    var passwordTextField: UITextField?
    
    // 2.  
    let alertController = UIAlertController(
      title: "Log in",
      message: "Please enter your credentials",
      preferredStyle: UIAlertControllerStyle.Alert)
    
    // 3.  
    let loginAction = UIAlertAction(
      title: "Log in", style: UIAlertActionStyle.Default) {
        (action) -> Void in
        
          if let username = usernameTextField?.text {
            print(" Username = \(username)")
          } else {
            print("No Username entered")
          }
        
          if let password = passwordTextField?.text {
            print("Password = \(password)")
          } else {
            print("No password entered")
          }
    }
    
    // 4.
    alertController.addTextFieldWithConfigurationHandler {
      (txtUsername) -> Void in
        usernameTextField = txtUsername
        usernameTextField!.placeholder = "<Your username here>"
    }
    
    alertController.addTextFieldWithConfigurationHandler {
      (txtPassword) -> Void in
        passwordTextField = txtPassword
        passwordTextField!.secureTextEntry = true
        passwordTextField!.placeholder = "<Your password here>"
    }
    
    // 5.
    alertController.addAction(loginAction)
    self.presentViewController(alertController, animated: true, completion: nil)
  }
  1. 建立兩個可選類型的 UITextField 變量用於警告彈窗。翻譯

  2. 建立一個 Alert 樣式的 AlertController。code

  3. 建立一個 Alert Action,閉包體中執行以下行爲:將 textField 輸入的信息打印到終端中。

  4. addTextFieldWithConfigurationHandler 方法用於添加文本輸入框(text input fields),閉包接收 Text Filed 做爲參數變量。

  5. 將登陸動做添加到 AlertController 中,同時呈現該控制器。

構建並運行該工程,點擊 Login 按鈕,填充 AlertController 中的 username 和 password 字段。輸入內容隨之打印到終端中。

你能夠前往 ioscreator 的 GitHub 倉庫下載 IOS9TextFieldAlertControllerTutorial 源代碼。

本文由 SwiftGG 翻譯組翻譯,已經得到做者翻譯受權,最新文章請訪問 http://swift.gg

相關文章
相關標籤/搜索