Creating A Numbered List In UITextView Swift 3

2019-07-30 08:15发布

I am trying to make a numbered list out of the information the user inputs into a UITextView. For example,

  1. List item one
  2. List item two
  3. List item three

Here is the code that I have tried but does not give me the desired effect. 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
}

as suggested here: How to make auto numbering on UITextview when press return key in swift but had no success.

Any help is much appreciated.

标签: swift3 xcode8
1条回答
ゆ 、 Hurt°
2楼-- · 2019-07-30 08:29

You can subclass UITextView, override method willMove(toSuperview and add an observer for UITextViewTextDidChange with a selector that break up your text into lines enumerating and numbering it accordingly. Try like this:

class NumberedTextView: UITextView {
    override func willMove(toSuperview newSuperview: UIView?) {
        frame = newSuperview?.frame.insetBy(dx: 50, dy: 80) ?? frame
        backgroundColor = .lightGray
        NotificationCenter.default.addObserver(self, selector: #selector(textViewDidChange), name: .UITextViewTextDidChange, object: nil)
    }
    func textViewDidChange(notification: Notification) {
        var lines: [String] = []
        for (index, line) in text.components(separatedBy: .newlines).enumerated() {
            if !line.hasPrefix("\(index.advanced(by: 1))") &&
                !line.trimmingCharacters(in: .whitespaces).isEmpty {
                lines.append("\(index.advanced(by: 1)). " + line)
            } else {
                lines.append(line)
            }
        }
        text = lines.joined(separator: "\n")
        // this prevents two empty lines at the bottom
        if text.hasSuffix("\n\n") {   
            text = String(text.characters.dropLast())
        }
    }
}

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let textView = NumberedTextView()
        view.addSubview(textView)
    }
}
查看更多
登录 后发表回答