在 UITextView 中按下 return 按钮时如何调用自定义函数?

How can I call a custom function when the return button is pressed within a UITextView?

我正在尝试调试一个问题,即按 return 键不会触发文本视图更改,结果会弄乱我的 UITextView 中的 NSAttributedString。每当我按下 return 按钮时,我的 UITextView 都会计算行数,并且出于某种原因认为图像只有 1 行。

您可以使用 textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) 调用自定义函数。

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        textView.delegate = self
    }

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

        if text == "\n" {
            print("new line")
            // Call your custom function
        }

        return true
    }