borderStyle:.none、.line、.bezel、.roundedRect(須設定才顯示邊框)。background / disabledBackground:自訂背景圖片(會忽略 borderStyle)。backgroundColor:背景色。placeholder:佔位提示文字。font、textColor:文字樣式。clearButtonMode:清除按鈕顯示時機(.never、.whileEditing、.unlessEditing、.always)。textAlignment、contentVerticalAlignment:水平/垂直對齊。adjustsFontSizeToFitWidth、minimumFontSize:自動縮字適應寬度。keyboardType:.default、.numberPad、.emailAddress、.decimalPad、.twitter 等 11 種。secureTextEntry:密碼模式(顯示黑點)。autocorrectionType、autocapitalizationType:自動修正、首字母大寫。returnKeyType:Return 鍵標題(.done、.go、.search、.next、.send 等)。keyboardAppearance:.default(淺灰)、.dark(深灰)。let imgView = UIImageView(image: UIImage(named: "icon"))
imgView.contentMode = .center
textField.leftView = imgView
textField.leftViewMode = .always
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
// 按 Return 收鍵盤
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// 輸入前驗證(可攔截特定字元)
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
// 例:僅允許數字
let allowed = CharacterSet.decimalDigits
return string.unicodeScalars.allSatisfy(allowed.contains)
}
// 編輯開始/結束回調
func textFieldDidBeginEditing(_ textField: UITextField) { }
func textFieldDidEndEditing(_ textField: UITextField) { }
}
覆寫下列方法可完全控制佈局:
textRect(forBounds:)、editingRect(forBounds:):文字/編輯區域。placeholderRect(forBounds:):佔位符區域。borderRect(forBounds:)、clearButtonRect(forBounds:)、leftViewRect(forBounds:)、rightViewRect(forBounds:)。drawText(in:)、drawPlaceholder(in:):自訂繪製。secureTextEntry = true 後切換回明文需重設字體,否則字體可能變粗。becomeFirstResponder() 呼叫時機需在 view 已加入視圖層級之後。inputView、inputAccessoryView 自訂鍵盤/工具列更靈活。善用屬性與委託,即可建立符合人體工學、符合品牌風格的輸入介面。