JKSwiftExtension 中UITextView+Extension
和 UITextField+Extension
有源码
- 目录:
- 1、背景介绍
- 2、使用
一、背景介绍
平时在开发中免不了限制输入的字符个数,如果涉及到(高亮和九宫格数字<➋➌➍➎➏➐➑➒>的问题)中的时候就会有各种问题,所以我们要处理这种情况
二、UITextView&UITextField 使用
- 2.1、UITextView+Extension扩展 和 UITextField+Extension扩展
public extension JKPOP where Base: UITextView { // MARK: 3.1、限制字数的输入(提示在:- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;方法里面调用) /// 限制字数的输入 /// - Parameters: /// - range: 范围 /// - text: 输入的文字 /// - maxCharacters: 限制字数 /// - regex: 可输入内容(正则) /// - Returns: 返回是否可输入 func inputRestrictions(shouldChangeTextIn range: NSRange, replacementText text: String, maxCharacters: Int, regex: String?) -> Bool { guard !text.isEmpty else { return true } guard let oldContent = self.base.text else { return false } if let _ = self.base.markedTextRange { /* let selectedRange = textView.markedTextRange let beginning = textView.beginningOfDocument let selectionStart = selectedRange.start let selectionEnd = selectedRange.end let location = textView.offset(from: beginning, to: selectionStart) let length = textView.offset(from: selectionStart, to: selectionEnd) print("location:\(location) length:\(length)") let selectText = textView.text(in: selectedRange) print("高亮部分的文字:\(selectText ?? "高亮没有文字")") print("有range-----------:YES \(selectedRange) 开始:\(selectedRange.start) 内容:\(oldContent) 长度:\(oldContent.count) 新的内容:\(text) 长度:\(text.count) 是否包含emoji表情:\(text.fb.containsEmoji()) range:\(range)") */ // print("🚀有range---------内容:\(oldContent) 长度:\(oldContent.count) 新的内容:\(text) 长度:\(text.count) range:\(range)") // 有高亮 if range.length == 0 { // 联想中 return oldContent.count + 1 <= maxCharacters } else { // 正则的判断 if let weakRegex = regex, !JKRegexHelper.match(text, pattern: weakRegex) { return false } // 联想选中键盘 let allContent = oldContent.jk.sub(to: range.location) + text if allContent.count > maxCharacters { let newContent = allContent.jk.sub(to: maxCharacters) // print("content1:\(allContent) content2:\(newContent)") self.base.text = newContent return false } } } else { guard !text.jk.isNineKeyBoard() else { return true } // 正则的判断 if let weakRegex = regex, !JKRegexHelper.match(text, pattern: weakRegex) { return false } // print("没有range---------:NO 内容:\(oldContent) 长度:\(oldContent.count) 新的内容:\(text) 长度:\(text.count) range:\(range)") // 2、如果数字大于指定位数,不能输入 guard oldContent.count + text.count <= maxCharacters else { return false } } return true } }
- 2.2、使用:我们以:UItextView为例,在
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
里面调用
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return textView.inputRestrictions(shouldChangeTextIn: range, replacementText: text, maxCharacters: maxCharacters, regex: regex) } func textViewDidChange(_ textView: UITextView) { print("字符数量:\(textView.text.count > maxCharacters ? maxCharacters : textView.text.count)") }