簡體   English   中英

如何檢查文本字段在 Swift 中是否有多個字母?

[英]How to check if textfield has more than one letter in Swift?

我正在 Swift 中處理一個文本字段,我將要實現的是禁用導航按鈕,除非文本字段中有 0 個字符,如果文本字段中有 1 個以上的字母,則在文本字段上添加刪除按鈕文本字段,如 iOS 默認日歷應用程序。

當標題文本字段中沒有字母時,欄按鈕項“添加”被禁用。

在此處輸入圖片說明

啟用“添加”按鈕並在標題文本字段中有 1+ 個字母時顯示刪除按鈕。

在此處輸入圖片說明

我查看了文本字段委托方法,我想我可以通過使用 shouldChangeCharactersIn 方法(?)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // check if there is a letter in the text field
    // if there is, enable the Add button and show delete icon
    // if there is not, disable the add button and hide the delete icon
    return true
}

我想知道是否還有其他方法可以實現此功能? 我想每當在文本字段上鍵入/刪除一個字母時,每次都會調用上面的函數,所以我想知道是否有其他方法可以輕松實現這些東西。

 func textFieldDidChangeSelection(_ textField: UITextField) {
    validateTextField(text:textField.tex)
}

您的方法 shouldChangeCharactersIn 有時無法正常工作,因此可以使用此方法創建一個接收文本並禁用和啟用導航欄和刪除按鈕的功能,例如

func validateTextField(text:String) {
  if text.count > 1 {
    textField.clearButtonMode = .whileEditing
  } else if text.count <= 1 {
     textField.clearButtonMode = .never
  } else if text.count < 1 {
     navigationItem.leftBarButtonItem.tintColor = .lightGray
  }

您可以對特定的文本字段文本計數使用故事板方法。

1.Ctrl + Click on the textfield in interface builder.
  1. 從 EditingChanged 拖動到助手視圖中的視圖控制器類內部。

在此處輸入圖片說明

3. 命名您的函數(例如“textFieldEditingChanged”)並單擊連接。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM