UITextView字符剩余

时间:2016-02-02 07:29:36

标签: ios swift uitextview uitextviewdelegate

如何为UILabel设置UITextView上剩余的字符?

我已经为UITextField完成了此操作,但相同的代码无效..

这就是我的尝试:

func textView(textView: UITextView, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
 {
        if string == ""
        {
            if plainTextView.text!.characters.count == 0
            {
                charCount = 0
                countLabel.text = String(format: "%i Characters Left", maxLength - charCount)
                return false
            }
            charCount = (plainTextView.text!.characters.count - 1)
            countLabel.text = String(format: "%i Characters Left", maxLength - charCount)
            return true
        }
        else
        {
            charCount = (plainTextView.text!.characters.count + 1)
            countLabel.text = String(format: "%i Characters Left", maxLength - charCount)

            if charCount >= maxLength + 1
            {
                charCount = maxLength
                countLabel.text = String(format: "%i Characters Left", maxLength - charCount)
                return false;
            }
        }
        return true
    }

有什么建议吗?

3 个答案:

答案 0 :(得分:4)

试试这个

func textViewDidChange(textView: UITextView) {
    countLabel.text = "\(200 - textView.text.characters.count)"
}


 func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
return textView.text.characters.count + (text.characters.count - range.length) <= 200
}

答案 1 :(得分:0)

雨燕5

extension AddProperty2ViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        p_summary_line_textview.text = "\(5000 - textView.text.count)"
    }


    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        return textView.text.count + (text.count - range.length) <= 5000
    }

}

答案 2 :(得分:0)

func textViewDidBeginEditing(_ textView: UITextView) {
    shrinkText()
}

func textViewDidChange(_ textView: UITextView) {
    shrinkText()
}

func textViewDidEndEditing(_ textView: UITextView) {
    shrinkText()
}


func shrinkText() {
    sendButton.isEnabled = reviewTextField.text == "" ? false : true
    
    var text = ""
    var counter = 0
    
    if reviewTextField.text.count > limit {
        reviewTextField.text.forEach {
            if counter < limit {
                counter += 1
                text.append($0)
            } else {
                return
            }
        }
        reviewTextField.text = text
    }
    counterLabel.text = "\(reviewTextField.text.count) / \(limit)"
}