1. 程式人生 > >[Xcode10 實際操作]四、常用控制元件-(8)UITextField控制元件的使用

[Xcode10 實際操作]四、常用控制元件-(8)UITextField控制元件的使用

本文將演示文字輸入框控制元件的基本用法。

文字輸入框主要用來接收和顯示使用者輸入的內容。

在專案導航區,開啟檢視控制器的程式碼檔案【ViewController.swift】

 1 import UIKit
 2 
 3 //新增文字框代理協議,
 4 //使用協議中的方法,在完成文字框文字的輸入後,隱藏系統鍵盤的顯示
 5 class ViewController: UIViewController, UITextFieldDelegate {
 6 
 7     override func viewDidLoad() {
 8         super.viewDidLoad()
9 // Do any additional setup after loading the view, typically from a nib. 10 //建立一個位置在(60,80),尺寸為(200,30)的顯示區域 11 let rect = CGRect(x: 60, y: 80, width: 200, height: 30) 12 //初始化文字輸入框物件,並設定其位置和尺寸 13 let textField = UITextField(frame: rect) 14 15 //設定文字框物件的邊框樣式為圓角矩形
16 textField.borderStyle = UITextField.BorderStyle.roundedRect 17 //設定文字框的佔位符屬性,用來描述輸入欄位預期值的提示資訊, 18 //該提示會在輸入欄位為空時顯示,並會在欄位獲得焦點時小時 19 textField.placeholder = "Your Email" 20 //關閉文字框物件的語法錯誤提示功能 21 textField.autocorrectionType = UITextAutocorrectionType.no
22 //設定在輸入文字時,在鍵盤面板上,回車按鈕的型別。 23 textField.returnKeyType = UIReturnKeyType.done 24 //設定文字框物件右側的清除按鈕,僅在編輯狀態時顯示 25 textField.clearButtonMode = UITextField.ViewMode.whileEditing 26 //設定文字框物件的鍵盤型別,為系統提供的郵箱地址型別 27 textField.keyboardType = UIKeyboardType.emailAddress 28 //設定文字框物件的鍵盤為暗色主題 29 textField.keyboardAppearance = UIKeyboardAppearance.dark 30 31 //設定文字框物件的代理為當前檢視控制器 32 textField.delegate = self 33 34 //將文字框物件,新增到當前檢視控制器的根檢視 35 self.view.addSubview(textField) 36 } 37 38 //新增一個方法,當用戶按下鍵盤上的回車鍵時,呼叫此方法。 39 func textFieldShouldReturn(_ textField: UITextField) -> Bool { 40 //當用戶按下鍵盤上的回車鍵時, 41 //文字框失去焦點,鍵盤也將自動隱藏 42 textField.resignFirstResponder() 43 //在方法的末尾返回一個布林值 44 return true 45 } 46 47 override func didReceiveMemoryWarning() { 48 super.didReceiveMemoryWarning() 49 // Dispose of any resources that can be recreated. 50 } 51 }