欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Swift 4.1】 UITextView 禁止输入Emoji表情,并且控制字数

程序员文章站 2023-12-23 15:31:46
...
extension String{
/// 判断是不是Emoji
    ///
    /// - Returns: true false
    func containsEmoji()->Bool{
        for scalar in unicodeScalars {
            switch scalar.value {
            case 0x1F600...0x1F64F,
                 0x1F300...0x1F5FF,
                 0x1F680...0x1F6FF,
                 0x2600...0x26FF,
                 0x2700...0x27BF,
                 0xFE00...0xFE0F:
                return true
            default:
                continue
            }
        }

        return false
    }

/// 判断是不是Emoji
    ///
    /// - Returns: true false
    func hasEmoji()->Bool {

        let pattern = "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"
        let pred = NSPredicate(format: "SELF MATCHES %@",pattern)
        return pred.evaluate(with: self)
    }

/// 判断是不是九宫格
    ///
    /// - Returns: true false
    func isNineKeyBoard()->Bool{
        let other : NSString = "➋➌➍➎➏➐➑➒"
        let len = self.length
        for i in 0 ..< len {
            if !(other.range(of: self).location != NSNotFound) {
                return false
            }
        }

        return true
    }


    /// 然后是去除字符串中的表情
    ///
    /// - Parameter text: text
    func disable_emoji(text : NSString)->String{
        do {
            let regex = try NSRegularExpression(pattern: "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]", options: NSRegularExpression.Options.caseInsensitive)

            let modifiedString = regex.stringByReplacingMatches(in: text as String, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, text.length), withTemplate: "")

            return modifiedString
        } catch {
            print(error)
        }
        return ""
    }
}

UITextViewDelegate中
let limitMaxWord = 10

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

        if text.isNineKeyBoard() {
            return true
        }else{
            if text.hasEmoji() || text.containsEmoji() {
                return false
            }
        }

        if textView.textInputMode?.primaryLanguage == "emoji" || !((textView.textInputMode?.primaryLanguage) != nil){
            return false
        }

        if text.length > 0 {
            quesDetualTextView.viewWithTag(8732)?.alpha = 0;
        }

        /// 选择区域
        if let selectedRange = textView.markedTextRange {
            if let pos = textView.position(from: selectedRange.start, offset: 0) {
                /// 获取高亮部分内容
                //        let selectedText = textView.text(in: selectedRange)
                let startOffset = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
                let endOffset   = textView.offset(from: textView.beginningOfDocument, to: selectedRange.end)
                let offsetRange = NSMakeRange(startOffset, endOffset - startOffset)
                if offsetRange.location < limitMaxWord{
                    return true
                }else{
                    return false
                }
            }
        }

        let str = textView.text + text
        if str.length > limitMaxWord {
            let rangeIndex = (str as NSString).rangeOfComposedCharacterSequence(at: limitMaxWord)
            if rangeIndex.length == 1{
                textView.text = str.substringToIndex(limitMaxWord)
                textNumberLabel.text = "\(textView.text.length)/\(limitMaxWord)字"
            }else{
                let renageRange = (str as NSString).rangeOfComposedCharacterSequences(for: NSMakeRange(0, limitMaxWord))
                textView.text = str.substringWithRange(renageRange)

            }
            return false
        }
        return true
    }

func textViewDidChange(_ textView: UITextView) {

        /// 选择区域
        if let selectedRange = textView.markedTextRange {

            //获取高亮部分
            if let pos = textView.position(from: selectedRange.start, offset: 0) {
                //如果在变化中是高亮部分在变,就不要计算字符了
                return
            }
        }

        if textView.text.length > limitMaxWord {
            textView.text = textView.text.substringToIndex(limitMaxWord)
        }
        textNumberLabel.text = "\(textView.text.length)/\(limitMaxWord)字"
    }

上一篇:

下一篇: