代码之家  ›  专栏  ›  技术社区  ›  lurning too koad

如何获得给定特定NSRange的字符串的UTF8编码字节计数?

  •  0
  • lurning too koad  · 技术社区  · 3 年前

    要获得字符串的UTF8编码字节计数,我只需执行以下操作。

    let str = "it's 🌮 time"
    let totalUTF8EncodedBytes = str.utf8.count
    
    print(totalUTF8EncodedBytes) // 14
    

    但是,如果给我一个 NSRange 对于这个字符串,我如何获得该范围的UTF8编码字节计数?

    为了添加一些上下文,我想用字符限制和字节限制来限制输入到文本视图中的字符。字符限制已完成。字节限制在技术上也有效,但当粘贴一个应该在现有文本范围的字节限制内的文本块时,它会在应该返回true时返回false,因为它没有考虑该范围。

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if let charLimit = characterLimit {
            let currentChars = textView.text.count
            let newChars = text.count - range.length
            let totalChars = currentChars + newChars
            return totalChars <= charLimit
        }
        
        if let byteLimit = utf8EncodedByteLimit {
            let currentBytes = textView.text.utf8.count
            let newBytes = text.utf8.count
            let totalBytes = currentBytes + newBytes
            return totalBytes <= byteLimit
        }
        return false
    }
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   HangarRash    3 年前

    您所需要做的就是从范围中获取子字符串:

    let subStr = (str as NSString).substring(with: range)
    

    然后你可以得到 utf8.count 属于 subStr ,或者在一行中完成所有操作:

    let subCount = (str as NSString).substring(with: range).utf8.count
    

    但为了你 shouldChangeTextIn ,您可以简单地执行以下操作:

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let newStr = (textView.text! as NSString).replacingCharacters(in: range, with: text)
        if let charLimit = characterLimit {
            return newStr.count <= charLimit
        }
    
        if let byteLimit = utf8EncodedByteLimit {
            return newStr.utf8.count <= byteLimit
        }
    
        return false
    }