清除 Swift 中 UITextView 的内容
Clear the content of UITextView in Swift
我的应用程序中有一个 UITextView
和一个 UIButton
,我试图在 UIButton
时清除 UITextView
的文本内容被点击了。
我的代码:
@IBOutlet weak var textView: UITextView!
@IBAction func ClearButtonTapped(_ sender: UIButton) {
// I want to clear the text content of textView
}
在 UITextView
class 中是否有 内置 函数?我在 Xcode.
中搜索 UITextView
class 时没有找到任何内容
我的应用程序在 Xcode 10.1 和 Swift 4.2 上。
我没有找到现成的函数来清除 UITextView
的文本内容,所以我创建了这段代码来做到这一点:
UITextView
变量:
@IBOutlet weak var textView: UITextView!
函数清除 UITextView
:
@IBAction func ClearButtonTapped(_ sender: UIButton) {
textView.selectAll(textView)
if let range = textView.selectedTextRange { textView.replace(range, withText: "") }
}
点击清除按钮时,该函数会检查 UITextView
中是否有任何文本,如果有,它将 select UITextView
中的所有文本并将其替换为空 String
.
编辑:
还有一个简单的方法,不知为何,我之前试过没有成功(可能是因为Xcode 10.1的bug),但是这样,如果用户不小心点击了清除按钮,就无法撤消它:
@IBAction func ClearButtonTapped(_ sender: UIButton) {
textView.text = ""
}
或扩展名:
extension UITextView {
func clear() {
self.text = ""
}
}
想清除文本时调用textView.clear()
。
小改进:
textView.text = nil
尝试使用 textView.text = ""
。如果这不起作用,则可能是您使用了占位符。尝试 textView.placeholder = ""
我的应用程序中有一个 UITextView
和一个 UIButton
,我试图在 UIButton
时清除 UITextView
的文本内容被点击了。
我的代码:
@IBOutlet weak var textView: UITextView!
@IBAction func ClearButtonTapped(_ sender: UIButton) {
// I want to clear the text content of textView
}
在 UITextView
class 中是否有 内置 函数?我在 Xcode.
UITextView
class 时没有找到任何内容
我的应用程序在 Xcode 10.1 和 Swift 4.2 上。
我没有找到现成的函数来清除 UITextView
的文本内容,所以我创建了这段代码来做到这一点:
UITextView
变量:
@IBOutlet weak var textView: UITextView!
函数清除 UITextView
:
@IBAction func ClearButtonTapped(_ sender: UIButton) {
textView.selectAll(textView)
if let range = textView.selectedTextRange { textView.replace(range, withText: "") }
}
点击清除按钮时,该函数会检查 UITextView
中是否有任何文本,如果有,它将 select UITextView
中的所有文本并将其替换为空 String
.
编辑:
还有一个简单的方法,不知为何,我之前试过没有成功(可能是因为Xcode 10.1的bug),但是这样,如果用户不小心点击了清除按钮,就无法撤消它:
@IBAction func ClearButtonTapped(_ sender: UIButton) {
textView.text = ""
}
或扩展名:
extension UITextView {
func clear() {
self.text = ""
}
}
想清除文本时调用textView.clear()
。
小改进:
textView.text = nil
尝试使用 textView.text = ""
。如果这不起作用,则可能是您使用了占位符。尝试 textView.placeholder = ""