我正在 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
}
我想知道是否還有其他方法可以實作此功能?我想每當在文本欄位上輸入/洗掉一個字母時,每次都會呼叫上面的函式,所以我想知道是否有其他方法可以輕松實作這些東西。
uj5u.com熱心網友回復:
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
}
uj5u.com熱心網友回復:
您可以對特定的文本欄位文本計數使用故事板方法。
1.Ctrl Click on the textfield in interface builder.
- 從 EditingChanged 拖動到助手視圖中的視圖控制器類內部。

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

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/314721.html
