萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

UITextField 完整屬性與委託模式詳解:打造專業輸入體驗

UITextField 核心屬性速查表

外觀與樣式

  • 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) { }
}

進階:重繪自訂區域(Subclassing)

覆寫下列方法可完全控制佈局:

  • textRect(forBounds:)、editingRect(forBounds:):文字/編輯區域。
  • placeholderRect(forBounds:):佔位符區域。
  • borderRect(forBounds:)、clearButtonRect(forBounds:)、leftViewRect(forBounds:)、rightViewRect(forBounds:)。
  • drawText(in:)、drawPlaceholder(in:):自訂繪製。

常見坑點提醒

  • 設定 secureTextEntry = true 後切換回明文需重設字體,否則字體可能變粗。
  • becomeFirstResponder() 呼叫時機需在 view 已加入視圖層級之後。
  • iPad 上 inputView、inputAccessoryView 自訂鍵盤/工具列更靈活。

善用屬性與委託,即可建立符合人體工學、符合品牌風格的輸入介面。

copyright © 萬盛學電腦網 all rights reserved