1. 程式人生 > >[Swift通天遁地]二、表格表單-(9)快速建立一個美觀強大的表單

[Swift通天遁地]二、表格表單-(9)快速建立一個美觀強大的表單

本文將演示如何利用第三方庫,快速建立一個美觀強大的表單

首先確保在專案中已經安裝了所需的第三方庫。

點選【Podfile】,檢視安裝配置檔案。

1 platform :ios, '12.0'
2 use_frameworks!
3 
4 target 'DemoApp' do
5     source 'https://github.com/CocoaPods/Specs.git'
6     pod 'Eureka', '~> 2.0.0-beta.1'
7 end

根據配置檔案中的相關配置,安裝第三方庫。

然後點選開啟【DemoApp.xcworkspace】專案檔案。

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

現在開始編寫程式碼,建立一個表單。

 1 import UIKit
 2 //在當前的類檔案中引入已經安裝的第三方類庫
 3 import Eureka
 4 
 5 //修改當前檢視控制器類的父類的名稱
 6 class ViewController: FormViewController {
 7 
 8     override func viewDidLoad() {
 9         super.viewDidLoad()
10         
11         //表單中的元素是以段落進行劃分的。
12 //在此建立第一個段落。 13 form = Section("Section1") 14 //往第一個段落中新增一個文字行 15 <<< TextRow() 16 { 17 row in 18 //設定文字行的標識值, 19 //通過該標識值,可以獲得使用者輸入的內容 20 row.tag = "TextRow" 21 //
設定文字行的左側的標題文字 22 row.title = "Text Row" 23 //設定文字行的佔位文字 24 row.placeholder = "Enter text here" 25 } 26 27 //建立一個手機行,允許使用者在該行輸入一個手機號碼 28 <<< PhoneRow() 29 { 30 row in 31 //設定手機行的標識值 32 row.tag = "PhoneRow" 33 //設定手機行的左側的標題文字 34 row.title = "Phone Row" 35 //設定手機行的佔位文字 36 row.placeholder = "And numbers here" 37 } 38 39 //新增第二個表單段落 40 +++ Section("Section2") 41 42 //新增一個日期行,使用者可以在此設定日期的值 43 <<< DateRow() 44 { 45 row in 46 //設定日期行的標識值 47 row.tag = "DateRow" 48 //設定日期行的左側的標題文字 49 row.title = "Date Row" 50 //設定日期行的初始的值為當天的日期 51 row.value = NSDate() as Date 52 } 53 54 //建立一個按鈕控制元件,並設定按鈕的顯示區域。 55 //當用戶點選該按鈕時,將獲得使用者在表單中輸入的內容 56 let button = UIButton(frame: CGRect(x: 0, y: 280, width: 320, height: 40)) 57 //設定按鈕控制元件的背景顏色 58 button.backgroundColor = UIColor.orange 59 //設定按鈕控制元件的標題文字 60 button.setTitle("Get row values", for: .normal) 61 //給按鈕控制元件繫結點選事件 62 button.addTarget(self, 63 action: #selector(ViewController.getRowValues(_:)), 64 for: .touchUpInside) 65 66 //將按鈕控制元件新增到當前檢視控制器的根檢視 67 self.view.addSubview(button) 68 } 69 70 //新增一個方法,用來響應按鈕的點選事件 71 func getRowValues(_ button : UIButton) 72 { 73 //通過標識的值,獲得表單中的文字行 74 let row: TextRow? = form.rowBy(tag: "MyRowTag") 75 //獲得使用者在該位置輸入的內容 76 let value = row?.value 77 //在控制檯輸出該內容 78 print("MyRowTag:\(value)") 79 80 //獲得使用者在表單輸入的所有內容, 81 //該內容是一個字典物件。 82 let valuesDictionary = form.values() 83 //在控制檯輸出該字典內容 84 print("valuesDictionary:\(valuesDictionary)") 85 } 86 87 override func didReceiveMemoryWarning() { 88 super.didReceiveMemoryWarning() 89 // Dispose of any resources that can be recreated. 90 } 91 }