I have a UITextView
. I want to disable all line breaks in the text view, whether they're typed manually or if the user pastes text that contains line breaks, and replace each line break with a space (" ").
How would I go about doing this? What function should I be making use of?
You can use UITextViewDelegate
's textViewDidChange(_:)
method to listen whenever the text view's text changes. Inside here, you can then replace all occurrences of a newline (\n
) with an empty String (""
).
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
}
extension ViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
let text = textView.text.replacingOccurrences(of: "\n", with: "")
textView.text = text
}
}