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
    }

原文地址:https://blog.csdn.net/GY5338/article/details/127789757

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_38254.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

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