import UIKit private var textfieldd = UITextField() class TextFieldViewController: UIViewController,UITextFieldDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //設置大小 textfieldd.frame = CGRect(x: 0, y: 100, width: 300, height: 50) // 設置 樣式 (.none 無邊框 .line 直線邊框 .roundedRect 圓角矩形邊框 .bezel 邊線+陰影) textfieldd.borderStyle = .roundedRect //提示字 textfieldd.placeholder = "提示字" textfieldd.textColor = UIColor.blue textfieldd.font = UIFont.boldSystemFont(ofSize: 20) textfieldd.textAlignment = .right // 設置 文字超出文本框時自適應大小 textfieldd.adjustsFontSizeToFitWidth = true // 設置 最小可縮小的字號 textfieldd.minimumFontSize = 14 //清理按鈕 textfieldd.clearButtonMode = .whileEditing //鍵盤樣式 textfieldd.keyboardType = .default textfieldd.delegate = self self.view.addSubview(textfieldd) } ////////////////////////////////代理方法//////////////////////////////////// // 輸入框詢問是否能夠編輯 true 能夠編輯 false 不能編輯 func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { print("我要開始編輯了...") return true } // 該方法表明輸入框已經能夠開始編輯 進入編輯狀態 func textFieldDidBeginEditing(_ textField: UITextField) { print("我正在編輯狀態中...") } // 輸入框將要將要結束編輯 func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { print("我即將編輯結束...") return true } // 輸入框結束編輯狀態 func textFieldDidEndEditing(_ textField: UITextField) { print("我已經結束編輯狀態...") } // 文本框是否能夠清除內容 func textFieldShouldClear(_ textField: UITextField) -> Bool { return true } // 輸入框按下鍵盤 return 收回鍵盤 func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // 該方法當文本框內容出現變化時 及時獲取文本最新內容 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }