如何在 swift 中按 return 键时在 UITextview 上进行自动编号

How to make auto numbering on UITextview when press return key in swift

当用户按下[Return]键时需要显示数字。就像每个 line.Is 的序列号 [1,2 等] 有什么办法吗?

我尝试了以下代码

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

    var textview_text_nssring = textView.text as NSString




    // Add "1" when the user starts typing into the text field


    if  (range.location == 0 && textView.text.isEmpty ) {


        if text == "\n" {

            textView.text = "1."

            let cursor = NSMakeRange(range.location + 3, 0)
            textView.selectedRange = cursor
            return false
        }

        else {

            textView.text = NSString(format: "1. %@", text) as String
        }


    }




 return true

}

为当前行号声明一个 Int var 并像这样在 shouldChangeTextIn range 中使用它。

var currentLine: Int = 1 

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    // Add "1" when the user starts typing into the text field
    if  (textView.text.isEmpty && !text.isEmpty) {
        textView.text = "\(currentLine). "
        currentLine += 1
    }
    else {
        if text.isEmpty {
            if textView.text.characters.count >= 4 {
                let str = textView.text.substring(from:textView.text.index(textView.text.endIndex, offsetBy: -4))
                if str.hasPrefix("\n") {
                    textView.text = String(textView.text.characters.dropLast(3))
                    currentLine -= 1
                }
            }
            else if text.isEmpty && textView.text.characters.count == 3 {
                textView.text = String(textView.text.characters.dropLast(3))
                currentLine = 1
            }
        }
        else {
            let str = textView.text.substring(from:textView.text.index(textView.text.endIndex, offsetBy: -1))
            if str == "\n" {
                textView.text = "\(textView.text!)\(currentLine). "
                currentLine += 1
            }
        }

    }
    return true
}