[Xcode 實際操做]4、經常使用控件-(8)UITextField控件的使用

目錄:[Swift]Xcode實際操做html

本文將演示文本輸入框控件的基本用法。swift

文本輸入框主要用來接收和顯示用戶輸入的內容。ide

在項目導航區,打開視圖控制器的代碼文件【ViewController.swift】post

 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 }
相關文章
相關標籤/搜索