在UITextView Swift 3

时间:2017-04-11 21:23:48

标签: swift3 xcode8

我正在尝试从用户输入到UITextView的信息中创建一个编号列表。例如,

  1. 列出第一项
  2. 列出第二项
  3. 列出第3项
  4. 这是我尝试过的代码,但没有给我预期的效果。     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
    }
    

    如此处所示:How to make auto numbering on UITextview when press return key in swift但没有成功。

    非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以继承UITextView,覆盖方法willMove(toSuperview并为UITextViewTextDidChange添加一个观察者,使用一个选择器将您的文本分解为枚举和编号的行。请尝试这样:

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)
    }
}