简体   繁体   中英

Clear the content of UITextView in Swift

I have a UITextView and a UIButton in my app and I'm trying to get the text content of the UITextView to be cleared when the UIButton is tapped.

My code:

@IBOutlet weak var textView: UITextView!

@IBAction func ClearButtonTapped(_ sender: UIButton) {
        // I want to clear the text content of textView
    }

Is there built-in function for that, in the UITextView class? I didn't find anything when I searched the UITextView class in Xcode.

My app is on Xcode 10.1 and Swift 4.2.

小改进:

textView.text = nil

Try using textView.text = "" . If that's not working it could be that you're using a placeholder. Try textView.placeholder = ""

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM