UITextField限制长度

1、字符串截取

extension String {
    
    /// 截取字符串
    /// - Parameters:
    ///   - begin: 开始截取的索引
    ///   - count: 需要截取的个数
    /// - Returns: 字符串
    func substring(start: Int, _ count: Int) -> String {
        let begin = index(startIndex, offsetBy: max(0, start))
        let end = index(startIndex, offsetBy: min(count, start + count))
        return String(self[begin..<end])
    }
    
}

2、UITextField限制长度

    // MARK: - textField 长度裁剪
    static func clipTextFieldTextLength(textField: UITextField, limitNum: Int) -&gt; String? {
        
        var finalText = textField.text
        if let text = textField.text, limitNum > 0 &amp;&amp; text.count > limitNum {
            
            if let language = UITextInputMode.activeInputModes.first?.primaryLanguage, language == "zh-Hans", let range = textField.markedTextRange {
                
                
                let start = range.start
                let end = range.end
                
                let selLength = textField.offset(from: start, to: end)
                let contentLength = text.count - selLength

                if (contentLength > limitNum) {
                    finalText = text.substring(start: 0, limitNum)
                }
            } else {
                finalText = text.substring(start: 0, limitNum)
            }
            
        }
        return finalText
    }

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注