I didn't find a ready function to clear the text content of an UITextView
so I created this code to do that:
The UITextView
variable:
@IBOutlet weak var textView: UITextView!
Function to clear the UITextView
:
@IBAction func ClearButtonTapped(_ sender: UIButton) {
textView.selectAll(textView)
if let range = textView.selectedTextRange { textView.replace(range, withText: "") }
}
When the clear-button is tapped, the function checks is there any text in the UITextView
and if there is some, it will select all the text in the UITextView
and replace it with an empty String
.
EDIT:
There is also the simple way to do it, which, for some reason, didn't work when I tried it before (probably because the bugs in Xcode 10.1), but this way the user can't undo it, if they accidentally tap the clear button:
@IBAction func ClearButtonTapped(_ sender: UIButton) {
textView.text = ""
}
Or with extension:
extension UITextView {
func clear() {
self.text = ""
}
}
Call textView.clear()
when you want to clear the text.