如何在 UITextView 特定行的末尾插入换行符

How to insert line break at the end of specific line of UITextView

我有 10 行的 UITextView,现在我想在第 5 行的末尾插入换行符。怎么可能?

  • 将文本拆分为 components(separatedBy: .newlines)
  • 获取第 5 行(在索引 4 处!)
  • 获取文本中带range(of:)
  • 行的范围
  • 在范围的 upperBound 索引处插入换行符。

这里是:

 let textview = UITextView()
        textview.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
        textview.text = "djhgiruior seitii iuuiuy  yyt  yt tr dtre d grf hth yghj  jh u hu khku yi  hhhhh\nuiytuftftyftyfytf"
        textview.backgroundColor = .green
        self.view.addSubview(textview)
        

它会在 '\n' 之后换行。所以用这个