Swift TextView输入字数限制

Swift5 TextView输入字数限制。

/*
 设置代理
 textView.delegate = self
 字数限制
 limitCount = 10
 占位label
 placeholderLabel
 输入字数提示: 0/limitCount
 limitCountLabel
 */
extension MyTextView : UITextViewDelegate {
    public func textViewDidChange(_ textView: UITextView) {
        if textView.text.count > limitCount {
            // 获得已输出字数与正输入字母数
            let selectRange = textView.markedTextRange
            
            // 获取高亮部分 - 如果有联想词则解包成功
            if let selectRange = selectRange {
                let position =  textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
            
            let textContent = textView.text ?? ""
            let textNum = textContent.count
            
            // 截取
            if textNum > limitCount && limitCount > 0 {
                textView.text = string_prefix(index: limitCount, text: textContent)
            }
        }
        self.limitCountLabel.text =  "\(textView.text.count)/\(limitCount)"
    }

    public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        self.placeholderLabel.isHidden = true
        return true
    }

    public func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            self.placeholderLabel.isHidden = false
        } else {
            self.placeholderLabel.isHidden = true
        }
    }

    public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if textView.returnKeyType == .done {
            if text == "\n" {
                textView.resignFirstResponder()
            }
            return true
        }
        return true
    }
    
    // 字符串的截取 从头截取到指定index
    private func string_prefix(index:Int,text:String) -> String {
        if text.count <= index {
            return text
        } else {
            let index = text.index(text.startIndex, offsetBy: index)
            let str = text.prefix(upTo: index)
            return String(str)
        }
    }
}

Swift: Swift5

你可能感兴趣的:(iOS开发,swift,开发语言,ios)