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

馋奶兔 提交于 2019-12-23 05:35:12

问题


When user press [Return] key then need to display the number. Like serial numbers [1,2 etc] for each line.Is there any way to do that?

Following code I tried

 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

}

回答1:


Declare one Int var for current line number and use it inside shouldChangeTextIn range like this way.

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
}


来源:https://stackoverflow.com/questions/39951546/how-to-make-auto-numbering-on-uitextview-when-press-return-key-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!