Search code examples
iosswiftswift4

Replace all line breaks with a space in a UITextView


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?


Solution

  • 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
        }
    }
    
    Without textViewDidChange(_:) With textViewDidChange(_:)
    User hits return and a new line is added. When they paste a string containing a new line, the new line is also added. User hits return but no new line is added. Any pasted string that contains a new line removes the new line.