簡體   English   中英

Swift5:TextField 最小和最大字符限制驗證

[英]Swift5: TextField Minimum and Maximum Character Limit Validation

我正在嘗試驗證 TextField 中的最少 6 個字符和最多 20 個字符。 下面是代碼驗證。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let curruntCharachterCount = textField.text?.count ?? 0
    if range.length + range.location > curruntCharachterCount{
        return false
    }
    let newLength = curruntCharachterCount + string.count - range.length
    return newLength <= 20
}

我應該如何設置最小字符長度驗證。 請建議。

你可以像下面這樣

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if let text = textField.text,
           let textRange = Range(range, in: text) {
            let updatedText = text.replacingCharacters(in: textRange,with: string)
            if updatedText.count <= 6 {
                print("minimum 6")
            }else if updatedText.count >= 20{
                print("max 20")
                return false
            }
        }
        return true
    }

暫無
暫無

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

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